-
Notifications
You must be signed in to change notification settings - Fork 24k
/
Copy pathbuilder.py
1925 lines (1755 loc) · 77.9 KB
/
builder.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 abc
import collections
import contextlib
import dataclasses
import enum
import functools
import inspect
import logging
import operator
import re
import sys
import types
from typing import List, NamedTuple, Optional, Union
try:
import numpy as np
except ModuleNotFoundError:
np = None
import torch
from torch import SymInt
from torch._guards import GuardSource, TracingContext
from torch._ops import HigherOrderOperator
from torch._streambase import _EventBase, _StreamBase
from torch._subclasses.fake_tensor import FakeTensor, is_fake, maybe_get_fake_mode
from torch.fx.experimental.symbolic_shapes import (
_constrain_range_for_size,
DimDynamic,
RelaxedUnspecConstraint,
StatefulSymbolicContext,
SubclassSymbolicContext,
SymbolicContext,
)
from torch.fx.immutable_collections import immutable_list
from torch.nested._internal.nested_tensor import NestedTensor
from torch.utils._python_dispatch import is_traceable_wrapper_subclass
from torch.utils.weak import TensorWeakRef
from .. import config, mutation_guard, replay_record, skipfiles, trace_rules
from ..allowed_functions import (
is_allowed,
is_builtin_callable,
is_numpy,
is_user_defined_allowed,
)
from ..device_interface import get_registered_device_interfaces
from ..exc import InternalTorchDynamoError, unimplemented
from ..guards import GuardBuilder, install_guard, make_dupe_guard
from ..side_effects import SideEffects
from ..source import (
AttrSource,
ConstantSource,
ConvertIntSource,
GetItemSource,
GlobalWeakRefSource,
is_constant_source,
LocalSource,
NumpyTensorSource,
RandomValueSource,
Source,
TupleIteratorGetItemSource,
)
from ..utils import (
build_checkpoint_variable,
clone_input,
get_fake_value,
get_static_address_type,
global_key_name,
is_namedtuple,
is_typing,
is_utils_checkpoint,
istype,
odict_values,
preserve_rng_state,
tensor_always_has_static_shape,
tuple_iterator,
tuple_iterator_getitem,
tuple_iterator_len,
wrap_fake_exception,
)
from .base import MutableLocal, typestr, VariableTracker
from .builtin import BuiltinVariable
from .constant import ConstantVariable, EnumVariable
from .ctx_manager import (
AutocastModeVariable,
EventVariable,
NullContextVariable,
StreamVariable,
)
from .dicts import (
ConstDictVariable,
DataClassVariable,
DefaultDictVariable,
HFPretrainedConfigVariable,
PythonSysModulesVariable,
SetVariable,
)
from .distributed import (
DeviceMeshVariable,
PlacementClassVariable,
PlacementVariable,
ProcessGroupVariable,
)
from .functions import (
CollectiveFunctionRewriteVariable,
FunctoolsPartialVariable,
TritonKernelVariable,
UserFunctionVariable,
UserMethodVariable,
)
from .higher_order_ops import TorchHigherOrderOperatorVariable
from .lazy import LazyVariableTracker
from .lists import (
BaseListVariable,
ListVariable,
NamedTupleVariable,
RangeVariable,
RestrictedListSubclassVariable,
SizeVariable,
SliceVariable,
TupleIteratorVariable,
TupleVariable,
)
from .misc import (
AutogradFunctionContextVariable,
AutogradFunctionVariable,
ComptimeVariable,
GetAttrVariable,
GetSetDescriptorVariable,
InspectSignatureVariable,
LambdaVariable,
MethodWrapperVariable,
NumpyVariable,
PythonModuleVariable,
SavedTensorBox,
SkipFilesVariable,
TypingVariable,
)
from .nn_module import FSDPManagedNNModuleVariable, UnspecializedNNModuleVariable
from .optimizer import OptimizerVariable
from .tensor import (
NumpyNdarrayVariable,
SymNodeVariable,
TensorSubclassVariable,
TensorVariable,
UnspecializedPythonVariable,
)
from .torch import torch_special_class_types, TorchVariable
from .torch_function import build_torch_function_fn, TensorWithTFOverrideVariable
from .user_defined import (
KeyedJaggedTensorVariable,
UserDefinedClassVariable,
UserDefinedObjectVariable,
)
log = logging.getLogger(__name__)
DimList = List
class _missing:
pass
@dataclasses.dataclass
class GraphArg:
source: Source
# TODO: storing a SymInt here but not a FakeTensor is a pretty strange
# thing to do. Probably should have example (which stores an int) and
# fake_example
_example: Union[TensorWeakRef, torch.SymInt]
is_unspecialized: bool
fake_tensor: Optional[torch._subclasses.fake_tensor.FakeTensor]
# UnspecializedPythonVariable often masquerades as a tensor.
# We MUST NOT generate shape guard code
# that actually tries to access tensor properties on these values.
# is_tensor lets us tell if this graph arg actually is a tensor
# or not.
is_tensor: bool = True
# Sometimes, the Tensor we pass to example is freshly allocated (smh).
# Then we cannot only keep a weak reference to it. This lets you
# stash a strong reference too.
example_strong_ref: Optional[torch.Tensor] = None
@property
def example(self):
if isinstance(self._example, TensorWeakRef):
r = self._example()
assert r is not None
return r
else:
return self._example
def __post_init__(self):
if isinstance(self._example, torch.Tensor):
self._example = TensorWeakRef(self._example)
assert is_fake(self.fake_tensor)
def load(self, tx):
return self.source.reconstruct(tx)
def erase(self):
self._example = None
self.example_strong_ref = None
def __eq__(self, other):
return self.source.name() == other.source.name()
@dataclasses.dataclass
class FrameStateSizeEntry:
scalar: Optional[int]
size: Optional[List[int]]
class VariableBuilder:
"""Wrap a python value in a VariableTracker() instance"""
def __init__(
self,
tx,
source: Source,
):
assert (
source is not None
), "Consider SourcelessBuilder for ephemeral objects, usually objects created locally."
assert TracingContext.try_get() is not None, "Expected active TracingContext"
super().__init__()
self.tx = tx
self.source = source
self.name = source.name()
def __call__(self, value):
if value in self.tx.output.side_effects:
side_effect_result = self.tx.output.side_effects[value]
dup_guard = make_dupe_guard(self.source, side_effect_result.source)
if dup_guard:
self.install_guards(dup_guard)
return side_effect_result
vt = self._wrap(value)
vt.source = self.source
if self._can_lift_attrs_to_inputs(vt):
vt = self.tx.output.side_effects.track_object_existing(value, vt)
return vt
def _can_lift_attrs_to_inputs(self, vt):
if type(vt) in [
TensorVariable,
TensorWithTFOverrideVariable,
UserDefinedObjectVariable,
NumpyNdarrayVariable,
]:
return True
return False
@staticmethod
@functools.lru_cache(None)
def _common_constants():
return {
# We zero-one specialize shapes, so specialize these constants
# too
0,
1,
# NB: There used to be more constants here, but honestly it was
# pretty confusing. Note we specialize floats by default, and
# DON'T specialize ints by default. This all only matters with
# dynamic_shapes
}
def get_source(self):
return self.source
def install_guards(self, *guards):
source = self.get_source()
if (
isinstance(source, ConstantSource)
or source.guard_source() == GuardSource.CONSTANT
):
return None
install_guard(*[source.make_guard(guard) for guard in guards], skip=1)
return {}
def set_source_and_track_mutable(self, value, var):
assert isinstance(var, VariableTracker)
var.source = self.source
return self.tx.output.side_effects.track_mutable(value, var)
@classmethod
@functools.lru_cache(None)
def _type_dispatch(cls):
# NB: Careful not to close over self to avoid ref cycle from lru_cache
entries = [
(
(
torch.Tensor,
torch.nn.Parameter,
torch._subclasses.FakeTensor,
torch._subclasses.functional_tensor.FunctionalTensor,
),
cls.wrap_tensor,
),
((tuple, list, odict_values, collections.deque), cls.wrap_listlike),
(tuple_iterator, cls.wrap_tuple_iterator),
((slice, range), cls.wrap_slice_range),
(
(
int,
float,
bool,
type(None),
str,
torch.Size,
torch.device,
torch.dtype,
),
cls.wrap_literal,
),
]
if config.trace_numpy and np:
entries.append((np.ndarray, cls.wrap_numpy_ndarray))
result = {}
for ts, fn in entries:
for t in ts if isinstance(ts, tuple) else (ts,):
assert t not in result
result[t] = fn
return result
@classmethod
@functools.lru_cache(None)
def _id_dispatch(cls):
from ..comptime import comptime
entries = [
(
inspect.signature,
lambda self, value: LambdaVariable(
InspectSignatureVariable.create,
source=self.source,
**self.install_guards(GuardBuilder.CLOSURE_MATCH),
),
),
(comptime, lambda self, value: ComptimeVariable()),
(
dataclasses.fields,
lambda self, value: LambdaVariable(
_dataclasses_fields_lambda,
source=self.source,
**self.install_guards(GuardBuilder.FUNCTION_MATCH),
),
),
]
result = {}
for ts, fn in entries:
for t in ts if isinstance(ts, (tuple, list)) else (ts,):
assert t not in result
result[id(t)] = fn
return result
def _wrap(self, value):
# import here to avoid circular dependencies
from torch.utils._triton import has_triton
if has_triton():
from triton.runtime.autotuner import Autotuner
from triton.runtime.jit import JITFunction
else:
class JITFunction:
pass
class Autotuner:
pass
# Handle exact type() match
type_dispatch = self._type_dispatch().get(type(value))
if type_dispatch is not None:
return type_dispatch(self, value)
# Handle exact id() match
id_dispatch = self._id_dispatch().get(id(value))
if id_dispatch is not None:
return id_dispatch(self, value)
# Note - There are some nested values where types mismatch!
# We want to get those out and wrap those.
value = inspect.getattr_static(value, "_torchdynamo_inline", value)
# Everything else (NB: order matters!)
if is_traceable_wrapper_subclass(value) or istype(
value, config.traceable_tensor_subclasses
):
return self.wrap_tensor(value)
elif is_namedtuple(value):
return self.wrap_listlike(value)
elif value is torch.utils._pytree.SUPPORTED_NODES:
# For SUPPORTED_NODES, we guard on the dictionary version (PEP509)
# under the assumption that the values themselves don't change.
self.install_guards(GuardBuilder.DICT_VERSION)
result = {
k: UserDefinedObjectVariable(
value[k],
source=GetItemSource(self.get_source(), k),
)
for k in value.keys()
}
return ConstDictVariable(result, type(value))
elif value is sys.modules:
return PythonSysModulesVariable(source=self.source)
elif istype(
value, (dict, collections.defaultdict, collections.OrderedDict)
) and all(
ConstantVariable.is_literal(k)
or self.tensor_can_be_dict_key(k)
or isinstance(k, enum.Enum)
for k in value.keys()
):
if not value and self.get_source().is_nn_module():
# It is faster to guard on 'false' property than to guard
# on actual dict keys, but we can't do this fast guard in general because
# it omits a crucial type check that ensures the value is actually still a dict at runtime.
# Why is this OK for (specialized) nnmodules? We set up a setattr hook
# to check for module property mutations, which does a reasonable,
# but not completely secure job ensuring a property wasn't changed.
self.install_guards(GuardBuilder.BOOL_FALSE)
else:
self.install_guards(GuardBuilder.DICT_KEYS)
# store key variables in global location for reconstruction
for key in value.keys():
if self.tensor_can_be_dict_key(key):
self.tx.store_global_weakref(global_key_name(key), key)
def index_source(key):
if self.tensor_can_be_dict_key(key):
return GlobalWeakRefSource(global_key_name(key))
else:
return key
result = {
k: LazyVariableTracker.create(
value[k],
source=GetItemSource(self.get_source(), index_source(k)),
)
for k in value.keys()
}
if istype(value, collections.defaultdict):
result = DefaultDictVariable(
result,
type(value),
default_factory=self._wrap(value.default_factory),
source=self.source,
)
else:
result = ConstDictVariable(result, type(value))
return self.set_source_and_track_mutable(value, result)
elif isinstance(value, torch.nn.Module):
return self.wrap_module(value)
elif ConstantVariable.is_literal(value): # non-atomic literals
return self.wrap_literal(value)
elif istype(value, frozenset) and (
all(is_allowed(x) or ConstantVariable.is_literal(x) for x in value)
):
# For frozenset, we can guard by object ID instead of value
# equality, this allows us to handle non-literal values
self.install_guards(GuardBuilder.ID_MATCH)
return ConstantVariable.create(value=value, source=self.source)
elif isinstance(value, enum.Enum):
self.install_guards(GuardBuilder.ID_MATCH)
return EnumVariable(value=value, source=self.source)
elif is_builtin_callable(value):
self.install_guards(GuardBuilder.BUILTIN_MATCH)
return BuiltinVariable(value, source=self.source)
elif is_utils_checkpoint(value):
return build_checkpoint_variable(source=self.source)
elif isinstance(value, functools.partial):
func_src = AttrSource(self.get_source(), "func")
func_obj = VariableBuilder(self.tx, func_src)(value.func)
args = []
args_source = AttrSource(self.get_source(), "args")
for i, arg in enumerate(value.args):
args.append(
VariableBuilder(self.tx, GetItemSource(args_source, i))(arg)
)
keywords = {}
keywords_source = AttrSource(self.get_source(), "keywords")
for k, v in value.keywords.items():
keywords[k] = VariableBuilder(
self.tx, GetItemSource(keywords_source, k)
)(v)
install_guard(
self.get_source().make_guard(GuardBuilder.TYPE_MATCH),
keywords_source.make_guard(GuardBuilder.DICT_KEYS),
args_source.make_guard(GuardBuilder.LIST_LENGTH),
)
return FunctoolsPartialVariable(func_obj, args, keywords, original=value)
elif is_typing(value):
# typing.List, typing.Mapping, etc.
self.install_guards(GuardBuilder.ID_MATCH)
return TypingVariable(
value,
source=self.source,
)
elif np is not None and isinstance(value, np.generic):
# numpy array scalars: convert to 0D arrays
return self.wrap_numpy_ndarray(np.asarray(value))
elif is_numpy(value):
assert np
self.install_guards(
GuardBuilder.FUNCTION_MATCH
if callable(value)
else GuardBuilder.TYPE_MATCH
)
return NumpyVariable(value, source=self.source)
# NB: These can't be put in type_dispatch, they have to run later
elif CollectiveFunctionRewriteVariable.can_rewrite(value):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return CollectiveFunctionRewriteVariable.create(
self.tx,
value,
source=self.source,
)
elif istype(value, torch.autograd.function.FunctionMeta):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return AutogradFunctionVariable(
value,
source=self.source,
)
elif isinstance(value, torch.autograd.function.FunctionCtx):
saved_tensors_source = AttrSource(self.source, "saved_tensors")
install_guard(
self.source.make_guard(GuardBuilder.TYPE_MATCH),
saved_tensors_source.make_guard(GuardBuilder.LIST_LENGTH),
)
saved_tensors = [
VariableBuilder(self.tx, GetItemSource(saved_tensors_source, n))(v)
for n, v in enumerate(value.saved_tensors)
]
return self.tx.output.side_effects.track_object_existing(
value,
AutogradFunctionContextVariable(
value,
source=self.source,
saved_tensors=SavedTensorBox(saved_tensors),
),
)
elif (
isinstance(value, types.MethodType)
and istype(
getattr(value, "__self__", None), torch.autograd.function.FunctionMeta
)
and getattr(value, "__name__", "") == "apply"
and value == getattr(value.__self__, "apply", None)
):
# handle aliased autograd function `apply` calls
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return GetAttrVariable(
AutogradFunctionVariable(value.__self__, source=self.source),
"apply",
)
elif np and isinstance(value, np.number):
return self.wrap_unspecialized_primitive(value)
elif DataClassVariable.is_matching_object(value):
self.install_guards(GuardBuilder.TYPE_MATCH)
return DataClassVariable.wrap(self, value)
elif HFPretrainedConfigVariable.is_matching_object(value):
self.install_guards(GuardBuilder.TYPE_MATCH)
return HFPretrainedConfigVariable(value)
elif isinstance(value, HigherOrderOperator):
self.install_guards(GuardBuilder.TYPE_MATCH, GuardBuilder.NAME_MATCH)
return TorchHigherOrderOperatorVariable.make(value, source=self.source)
elif type(value).__name__ == "builtin_function_or_method" and isinstance(
value.__self__, torch_special_class_types
):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return TorchVariable(
value,
)
elif isinstance(value, _StreamBase):
self.install_guards(GuardBuilder.ID_MATCH)
return StreamVariable(
None,
value,
value.device.type,
source=self.source,
)
elif isinstance(value, _EventBase):
self.install_guards(GuardBuilder.ID_MATCH)
return EventVariable(
None,
value,
source=self.source,
)
elif (
isinstance(value, torch._C._TensorMeta)
and value in config.traceable_tensor_subclasses
):
return TensorSubclassVariable(value, source=self.source)
elif (
istype(value, contextlib.nullcontext)
and inspect.getattr_static(value, "enter_result", None) is None
):
self.install_guards(GuardBuilder.TYPE_MATCH)
return NullContextVariable(source=self.source)
elif KeyedJaggedTensorVariable.is_matching_object(value):
self.install_guards(GuardBuilder.TYPE_MATCH)
result = KeyedJaggedTensorVariable(value, source=self.source)
# TODO: this doing it manually is bad
return self.tx.output.side_effects.track_object_existing(value, result)
elif isinstance(value, torch.optim.Optimizer):
self.install_guards(GuardBuilder.TYPE_MATCH)
return OptimizerVariable(value, source=self.source)
elif ProcessGroupVariable.is_process_group(value):
self.install_guards(GuardBuilder.ID_MATCH)
return ProcessGroupVariable(value, source=self.source)
elif DeviceMeshVariable.is_device_mesh(value):
# TODO: see if we need to add custom guard instead of a simple ID_MATCH
self.install_guards(GuardBuilder.ID_MATCH)
return DeviceMeshVariable(value, source=self.source)
elif PlacementClassVariable.is_placement_type(value):
# TODO: see if we need to add custom guard instead of a simple ID_MATCH
self.install_guards(GuardBuilder.ID_MATCH)
return PlacementClassVariable(value, source=self.source)
elif PlacementVariable.is_placement(value):
# TODO: see if we need to add custom guard instead of a simple ID_MATCH
self.install_guards(GuardBuilder.ID_MATCH)
return PlacementVariable(
value,
source=self.source,
)
elif isinstance(value, torch.SymBool):
# Note: the idea here is to re-use the infra we've built for SymInt by simulating the
# user provided SymBool with a SymInt in dynamo.
# Concretely,
# 1. We create a SymInt in dynamo's shape_env, whose source is constructed as ConvertIntSource(self.source).
# so that guards on the SymInts can be effectively applied on the original SymBool in user program.
# 2. We create a SymBool based on the SymInt in dynamo's ShapeEnv. Because the original user program
# depends on the value being a SymBool. This allows dynamo to interpret the user's program correctly.
value_hint = value.node.require_hint()
new_source = ConvertIntSource(self.source)
new_symint = self.tx.output.shape_env.create_unspecified_symint_and_symbol(
int(value_hint),
new_source,
dynamic_dim=DimDynamic.DYNAMIC,
)
sym_node_proxy = self.tx.output.root_tracer.create_graph_input(
re.sub(r"[^a-zA-Z0-9]+", "_", self.name),
type(new_symint),
source=new_source,
)
sym_node_proxy.node.meta["grapharg"] = GraphArg(
new_source,
new_symint,
False,
None,
is_tensor=False,
example_strong_ref=new_symint,
)
self.tx.output.bound_symbols.add(new_symint.node.expr)
self.tx.output.tracked_fakes.append(
TrackedFake(new_symint, new_source, None)
)
return SymNodeVariable(
sym_node_proxy,
new_symint == 1,
)
elif isinstance(value, (JITFunction, Autotuner)):
self.install_guards(GuardBuilder.ID_MATCH)
return TritonKernelVariable(
value,
None, # No kernel idx provided
None, # No grid provided
source=self.source,
)
elif isinstance(value, torch.amp.autocast_mode.autocast):
self.install_guards(GuardBuilder.ID_MATCH)
return AutocastModeVariable(
target_values=[
value.device,
value.fast_dtype,
value._enabled,
value._cache_enabled,
],
source=self.source,
)
elif trace_rules.lookup(value) is not None:
if is_user_defined_allowed(value):
self.tx.output.has_user_defined_allowed_in_graph = True
return trace_rules.lookup(value).create_with_source(
value, source=self.source
)
elif is_allowed(value):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return TorchVariable(
value,
source=self.source,
)
elif (
istype(value, (type, types.FunctionType))
and skipfiles.check(value, is_inlined_call=True)
and not inspect.getattr_static(value, "_torchdynamo_inline", False)
and not inspect.getattr_static(value, "__script_if_tracing_wrapper", False)
):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return SkipFilesVariable(
value,
skipfiles.check_verbose(value, is_inlined_call=True).reason,
source=self.source,
)
elif istype(value, (types.FunctionType, torch.jit.ScriptFunction)):
self.install_guards(GuardBuilder.CLOSURE_MATCH)
return UserFunctionVariable(
value,
source=self.source,
)
elif isinstance(value, types.MethodType) and isinstance(
value.__self__, torch.nn.Module
):
# don't let MethodTypes fall through to UserDefinedObject,
# which doesn't support 'CALL_FUNCTION'
# TODO(whc): Why do we limit this to methods on NNModules?
# I don't have a good reason for this, but it preserves the existing behavior
# for MBartForConditionalGeneration, which generates many graph breaks and OOMs otherwise.
# I suspect we probably want to relax this check and dig deeper there.
# In order to construct a MethodVariable in Dynamo, we start with an actual method obj from python,
# but need to separately wrap its underlying `__func__` and its `self` argument. We wrap `self` here
# and then `__func__` gets wrapped inside UserMethodVariable.
self_obj = VariableBuilder(
self.tx, source=AttrSource(self.source, "__self__")
)(value.__self__)
assert self_obj and isinstance(
self_obj, VariableTracker
), "Failed to produce a valid self obj"
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return UserMethodVariable(
value.__func__,
self_obj,
source=self.source,
)
elif istype(value, (types.ModuleType, replay_record.DummyModule)):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return PythonModuleVariable(
value,
source=self.source,
)
elif isinstance(value, types.GetSetDescriptorType):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return GetSetDescriptorVariable(value)
elif isinstance(value, types.MethodWrapperType):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return MethodWrapperVariable(value)
elif issubclass(type(value), type):
self.install_guards(GuardBuilder.FUNCTION_MATCH)
return UserDefinedClassVariable(
value,
source=self.source,
)
elif RestrictedListSubclassVariable.is_matching_cls(type(value)):
self.install_guards(GuardBuilder.TYPE_MATCH, GuardBuilder.LIST_LENGTH)
return self.set_source_and_track_mutable(
value,
RestrictedListSubclassVariable(
[
LazyVariableTracker.create(
value=value[i], source=GetItemSource(self.source, i)
)
for i in range(len(value))
],
user_cls=type(value),
user_cls_source=AttrSource(self.source, "__class__"),
),
)
else:
self.install_guards(GuardBuilder.TYPE_MATCH)
result = UserDefinedObjectVariable(value, source=self.source)
if not SideEffects.cls_supports_mutation_side_effects(type(value)):
# don't allow STORE_ATTR mutation with custom __setattr__
return result
return self.tx.output.side_effects.track_object_existing(value, result)
def tensor_can_be_dict_key(self, value):
# only allow Parameter and another specific Tensor can be used as dict key
return (
isinstance(value, torch.nn.Parameter)
or isinstance(self.source, AttrSource)
and self.source.member == "state"
and isinstance(self.source.base, LocalSource)
)
def tensor_should_specialize(self):
return (
self.source
and isinstance(self.source, GetItemSource)
and isinstance(self.source.base, GetItemSource)
and self.source.base.index == "params"
and isinstance(self.source.base.base, GetItemSource)
and isinstance(self.source.base.base.base, AttrSource)
and self.source.base.base.base.member == "param_groups"
and isinstance(self.source.base.base.base.base, LocalSource)
and (
isinstance(
self.tx.f_locals[self.source.base.base.base.base.local_name],
torch.optim.Optimizer,
)
if self.source.base.base.base.base.local_name in self.tx.f_locals.keys()
else True
)
)
def wrap_listlike(self, value: Union[tuple, list, odict_values, NamedTuple]):
# One can index a tensor with a list/tuple. Therefore, we need to
# have a stricter match.
self.install_guards(GuardBuilder.LIST_LENGTH)
for item in value:
if item is value:
unimplemented("list elements are pointing to the list itself")
output = [
VariableBuilder(self.tx, GetItemSource(self.get_source(), i))(item)
for i, item in enumerate(value)
]
result = BaseListVariable.cls_for_instance(value)(
output, mutable_local=MutableLocal()
)
if istype(value, list):
return self.set_source_and_track_mutable(value, result)
return result
def wrap_tuple_iterator(self, value: tuple_iterator):
self.install_guards(GuardBuilder.TUPLE_ITERATOR_LEN)
output = [
VariableBuilder(self.tx, TupleIteratorGetItemSource(self.get_source(), i))(
tuple_iterator_getitem(value, i)
)
for i in range(tuple_iterator_len(value))
]
result = TupleIteratorVariable(
output, mutable_local=MutableLocal(), source=self.source
)
return self.set_source_and_track_mutable(value, result)
def wrap_slice_range(self, value: Union[slice, range]):
items = [
VariableBuilder(self.tx, AttrSource(self.get_source(), k))(
getattr(value, k)
)
for k in ("start", "stop", "step")
]
self.install_guards(GuardBuilder.TYPE_MATCH)
if isinstance(value, slice):
return SliceVariable(items, source=self.source)
else:
return RangeVariable(items, source=self.source)
def wrap_module(self, value: torch.nn.Module):
from ..eval_frame import OptimizedModule
if istype(value, OptimizedModule):
self.install_guards(GuardBuilder.TYPE_MATCH)
self.source = AttrSource(self.source, "_orig_mod")
return self.wrap_module(value._orig_mod)
if (
isinstance(value, (torch.nn.RNN, torch.nn.GRU, torch.nn.LSTM))
and not config.allow_rnn
):
unimplemented("TorchDynamo purposely graph breaks on RNN, GRU, LSTMs")
if mutation_guard.is_dynamic_nn_module(value):
# created dynamically, don't specialize on it
self.install_guards(GuardBuilder.TYPE_MATCH)
result = UnspecializedNNModuleVariable(value, source=self.source)
if not SideEffects.cls_supports_mutation_side_effects(type(value)):
# don't allow STORE_ATTR mutation with custom __setattr__
return result
return self.tx.output.side_effects.track_object_existing(value, result)
elif issubclass(
value.__class__, torch.nn.parallel.distributed.DistributedDataParallel
):
self.install_guards(GuardBuilder.TYPE_MATCH)
return UnspecializedNNModuleVariable(value)
elif getattr(value, "_is_fsdp_managed_module", False):
# See note [Dynamo treats FSDP wrapped modules as UnspecializedNNModule]
# in fully_sharded_data_parallel.py for more information
# we can't do this assert inside FSDP constructor,
# since we don't know yet whether dynamo will be used
assert getattr(
value, "_fsdp_use_orig_params", False
), "Dynamo only supports FSDP with use_orig_params=True"
# Note on FSDP guarding
# 1. We expect FSDP wrapping mutates an nn module irreversably (no way to de-wrap).
# 2. Eager FSDP already assumes (requires, but without enforcement) that users don't mutate their
# model parameters/structure after FSDP wrapping, because FSDP wouldn't notice or update its FlatParams.
#
# Due to (1), once we enter this path we expect not to go back nor have to guard on type
# or _is_fsdp_managed_module.
#
# TODO(whc) We could add a guard on the opposite case, where a user compiled/ran
# pre-FSDP-wrapped model, then wrapped, to ensure that we recompile with the FSDP handling.
#
# Due to (2), we skip guards on inner contents of fsdp_managed modules, by using FSDPNNModuleSource as the
# guard source. This behavior is gated on config.skip_fsdp_guards.
#
# ID_MATCH is required to disambiguate cases as simple as a unit test that constructs 2 models and wraps
# them differently with different FSDP configs. (test_dynamo_distributed.py -k test_fsdp_aot_eager)
self.install_guards(GuardBuilder.TYPE_MATCH, GuardBuilder.ID_MATCH)
return FSDPManagedNNModuleVariable(value, source=self.get_source())
else:
return self.tx.output.register_attr_or_module(
value,
self.name,
source=self.get_source(),
# Guards are added inside register_attr_or_module
)
def wrap_literal(self, value):
unspec = not config.specialize_int
if unspec and type(value) is torch.Size:
self.install_guards(GuardBuilder.LIST_LENGTH)
return SizeVariable(
[
VariableBuilder(self.tx, GetItemSource(self.get_source(), i))(v)
for i, v in enumerate(value)
]
)
elif unspec and type(value) is int:
# unspecializing int by default, but still
# specialize for the following conditions
if not TracingContext.get().force_unspec_int_unbacked_size_like and (
value in self._common_constants()
# Assume integers from global variables want to be specialized
or not self.source.guard_source().is_local()
# Assume that integers that came from NN modules want to be
# specialized (as we don't expect users to be changing the
# NN modules on the fly)
or self.source.guard_source().is_nn_module()
):
self.install_guards(GuardBuilder.CONSTANT_MATCH)
return ConstantVariable.create(value=value, source=self.source)
else:
return self.wrap_unspecialized_primitive(value)
else:
self.install_guards(GuardBuilder.CONSTANT_MATCH)
return ConstantVariable.create(value=value)
def assert_not_wrapped_by_this_graph(self, value: torch.Tensor):
if is_fake(value) and maybe_get_fake_mode(value) is self.tx.fake_mode:
raise InternalTorchDynamoError(
"Cannot wrap a Tensor that has already been",
"wrapped by this instance of Dynamo",
)
def wrap_tensor(self, value: torch.Tensor):
source = self.get_source()
# We cannot already be tracking the tensor, which implies
# it would have already been wrapped
assert value not in self.tx.output.side_effects
if (
source.guard_source().is_nn_module()
or get_static_address_type(value) is not None
) and not source.guard_source().is_fsdp_module():
self.assert_not_wrapped_by_this_graph(value)
return self.tx.output.register_attr_or_module(
value, self.name, source=source
)
if is_constant_source(source):
self.assert_not_wrapped_by_this_graph(value)
return self.tx.output.register_attr_or_module(
value,
re.sub(r"[^a-zA-Z0-9]+", "_", self.name),
source=source,