config.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. """
  2. Configuration module for TorchDynamo compiler and optimization settings.
  3. This module contains various configuration flags and settings that control TorchDynamo's
  4. behavior, including:
  5. - Runtime behavior flags (e.g., guard settings, specialization options)
  6. - Debugging and development options
  7. - Performance tuning parameters
  8. - Feature toggles for experimental features
  9. """
  10. import getpass
  11. import os
  12. import sys
  13. import sysconfig
  14. import tempfile
  15. from collections.abc import Callable
  16. from os.path import abspath, dirname
  17. from typing import Any, Literal, Optional, TYPE_CHECKING, Union
  18. from torch._environment import is_fbcode
  19. from torch.utils._config_module import Config, get_tristate_env, install_config_module
  20. # to configure logging for dynamo, aot, and inductor
  21. # use the following API in the torch._logging module
  22. # torch._logging.set_logs(dynamo=<level>, aot=<level>, inductor<level>)
  23. # or use the environment variable TORCH_LOGS="dynamo,aot,inductor" (use a prefix + to indicate higher verbosity)
  24. # see this design doc for more detailed info
  25. # Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit#
  26. # the name of a file to write the logs to
  27. # [@compile_ignored: debug]
  28. log_file_name: Optional[str] = None
  29. # [@compile_ignored: debug] Verbose will print full stack traces on warnings and errors
  30. verbose = os.environ.get("TORCHDYNAMO_VERBOSE", "0") == "1"
  31. # [@compile_ignored: runtime_behaviour] verify the correctness of optimized backend
  32. verify_correctness = False
  33. # need this many ops to create an FX graph (deprecated: not used)
  34. minimum_call_count = 1
  35. # turn on/off DCE pass (deprecated: always true)
  36. dead_code_elimination = True
  37. # Enable or disable side effect replay after graph execution.
  38. # When False, mutations to Python objects (lists, dicts, attributes) won't be
  39. # replayed after the compiled graph runs. This can cause correctness issues
  40. # if your code depends on these mutations being visible. This should probably
  41. # never be False by default. At the moment, only export will need it.
  42. replay_side_effects = True
  43. # Configure side effect warning level
  44. # If `silent`, we silently allow side effects
  45. # If `warn`, we warn side effects
  46. # If `error`, we error on side effects
  47. side_effect_replay_policy = "silent"
  48. # disable (for a function) when cache reaches this size
  49. # controls the maximum number of cache entries with a guard on same ID_MATCH'd
  50. # object. It also controls the maximum size of cache entries if they don't have
  51. # any ID_MATCH'd guards.
  52. # [@compile_ignored: runtime_behaviour]
  53. recompile_limit = 8
  54. # [@compile_ignored: runtime_behaviour] safeguarding to prevent horrible recomps
  55. accumulated_recompile_limit = 256
  56. # [@compile_ignored: runtime_behaviour] skip tracing recursively if cache limit is hit (deprecated: does not do anything)
  57. skip_code_recursive_on_recompile_limit_hit = True
  58. # raise a hard error if cache limit is hit. If you are on a model where you
  59. # know you've sized the cache correctly, this can help detect problems when
  60. # you regress guards/specialization. This works best when recompile_limit = 1.
  61. # This flag is incompatible with: suppress_errors.
  62. # [@compile_ignored: runtime_behaviour]
  63. fail_on_recompile_limit_hit = False
  64. cache_size_limit: int = Config(alias="torch._dynamo.config.recompile_limit")
  65. accumulated_cache_size_limit: int = Config(
  66. alias="torch._dynamo.config.accumulated_recompile_limit"
  67. )
  68. # (deprecated: does not do anything)
  69. skip_code_recursive_on_cache_limit_hit: bool = Config(
  70. alias="torch._dynamo.config.skip_code_recursive_on_recompile_limit_hit"
  71. )
  72. fail_on_cache_limit_hit: bool = Config(
  73. alias="torch._dynamo.config.fail_on_recompile_limit_hit"
  74. )
  75. # whether or not to specialize on int inputs. This only has an effect with
  76. # dynamic_shapes; when dynamic_shapes is False, we ALWAYS specialize on int
  77. # inputs. Note that assume_static_by_default will also cause ints to get
  78. # specialized, so this is mostly useful for export, where we want inputs
  79. # to be dynamic, but accesses to ints should NOT get promoted into inputs.
  80. specialize_int = False
  81. # Whether or not to specialize on float inputs. Dynamo will always promote
  82. # float inputs into Tensor inputs, but at the moment, backends inconsistently
  83. # support codegen on float (this is to be fixed).
  84. specialize_float = False
  85. # legacy config, does nothing now!
  86. dynamic_shapes = True
  87. use_lazy_graph_module = (
  88. os.environ.get("TORCH_COMPILE_USE_LAZY_GRAPH_MODULE", "1") == "1"
  89. )
  90. # This is a temporarily flag, which changes the behavior of dynamic_shapes=True.
  91. # When assume_static_by_default is True, we only allocate symbols for shapes marked dynamic via mark_dynamic.
  92. # NOTE - this flag can be removed once we can run dynamic_shapes=False w/ the mark_dynamic API
  93. # see [Note - on the state of mark_dynamic]
  94. assume_static_by_default = True
  95. # This flag changes how dynamic_shapes=True works, and is meant to be used in conjunction
  96. # with assume_static_by_default=True.
  97. # With this flag enabled, we always compile a frame as fully static for the first time, and, if we fail
  98. # any guards due to wobbles in shape, we recompile with *all* the wobbled shapes as being marked dynamic.
  99. automatic_dynamic_shapes = True
  100. # Valid options: "dynamic", "unbacked"
  101. automatic_dynamic_shapes_mark_as: Literal["dynamic", "unbacked"] = "dynamic"
  102. # log graph in/out metadata
  103. # This is only turned on for export today since we
  104. # know we are tracing a flat callable. later, this
  105. # can extended to other use cases as well.
  106. log_graph_in_out_metadata = False
  107. # This flag changes how the shapes of parameters are treated.
  108. # If this flag is set to True, then the shapes of torch.nn.Parameter as well as of torch.Tensor are attempted to be dynamic
  109. # If this flag is set to False, then the shapes of torch.nn.Parameter are assumed to be static,
  110. # while the shapes of torch.Tensor are assumed to be dynamic.
  111. force_parameter_static_shapes = True
  112. # This flag ensures that the shapes of a nn module are always assumed to be static
  113. # If the flag is set to True, then the shapes of a nn.module are assumed to be static
  114. # If the flag is set to False, then the shapes of a nn.module can be dynamic
  115. force_nn_module_property_static_shapes = True
  116. # Typically, if you mark_dynamic a dimension, we will error if the dimension
  117. # actually ended up getting specialized. This knob changes the behavior so
  118. # that we don't error at all. This is helpful for our CI where I'm using a
  119. # heuristic to mark batch dimensions as dynamic and the heuristic may get it
  120. # wrong.
  121. allow_ignore_mark_dynamic = False
  122. # Set this to False to assume nn.Modules() contents are immutable (similar assumption as freezing)
  123. guard_nn_modules = True
  124. # Uses CPython internal dictionary tags to detect mutation. There is some
  125. # overlap between guard_nn_modules_using_dict_tags and guard_nn_modules flag.
  126. # guard_nn_modules unspecializes the nn module instance and adds guard for each
  127. # relevant member of the nn modules. On the other hand,
  128. # guard_nn_modules_using_dict_tags specializes on each nn module instance but
  129. # uses low overhead dict version matching to detect mutations, obviating the
  130. # need to guard on members of the nn modules. With
  131. # guard_nn_modules_using_dict_tags, the guard_nn_modules is not really required
  132. # but kept around for debugging and discussing unspecializing nn module
  133. # variables.
  134. # TODO(janimesh, voz): Remove both of these flags (or at least guard_nn_modules)
  135. # once we have reached stability for the guard_nn_modules_using_dict_tags.
  136. guard_nn_modules_using_dict_tags = True
  137. # Flag to enable preparation for graph freezing, so that the named parameters and
  138. # buffers are passed as params_flat in tracing context by AOT autograd.
  139. # Non-Inductor backends can use this list for graph freezing.
  140. prepare_freezing = os.environ.get("TORCHDYNAMO_PREPARE_FREEZING", "0") == "1"
  141. # NOTE this has been deprecated, it does nothing now.
  142. traceable_tensor_subclasses: set[type[Any]] = set()
  143. # If a tensor subclass is put into this set, Dynamo will model its instasnces in
  144. # a very conservative and limited way (most likely causing lots of graph breaks
  145. # if one apply tensor ops on these instances). This is useful if you encounter
  146. # internal compiler errors from Dynamo which are caused by tensor subclasses,
  147. # and you are willing to tolerate potential graph breaks rather than hard error.
  148. nontraceable_tensor_subclasses: set[type[Any]] = set()
  149. # Suppress errors in torch._dynamo.optimize, instead forcing a fallback to eager.
  150. # This is a good way to get your model to work one way or another, but you may
  151. # lose optimization opportunities this way. Devs, if your benchmark model is failing
  152. # this way, you should figure out why instead of suppressing it.
  153. # This flag is incompatible with: fail_on_recompile_limit_hit.
  154. suppress_errors = bool(os.environ.get("TORCHDYNAMO_SUPPRESS_ERRORS", False))
  155. # Record and write an execution record of the current frame to a file
  156. # if an exception is encountered
  157. # @compile_ignored[debug]
  158. replay_record_enabled = os.environ.get("TORCH_COMPILE_REPLAY_RECORD", "0") == "1"
  159. # Rewrite assert statement in python with torch._assert
  160. rewrite_assert_with_torch_assert = True
  161. # Disable dynamo
  162. disable = os.environ.get("TORCH_COMPILE_DISABLE", "0") == "1"
  163. # [@compile_ignored: runtime_behaviour] Get a cprofile trace of Dynamo
  164. cprofile = os.environ.get("TORCH_COMPILE_CPROFILE", False)
  165. # Legacy config, does nothing now!
  166. skipfiles_inline_module_allowlist: dict[Any, Any] = {}
  167. """Allowlist of inline modules to skip during compilation.
  168. Legacy configuration that previously controlled which modules could be
  169. inlined during tracing. This configuration is deprecated and no longer used.
  170. :type: dict[Any, Any]
  171. :default: {}
  172. .. deprecated::
  173. This configuration is deprecated and does nothing now.
  174. .. note::
  175. DEPRECATED: This setting has no effect on current behavior.
  176. """
  177. # If a string representing a PyTorch module is in this ignorelist,
  178. # the `allowed_functions.is_allowed` function will not consider it
  179. # when creating a list of PyTorch functions that will appear in
  180. # FX IR.
  181. allowed_functions_module_string_ignorelist = {
  182. "torch.distributions",
  183. "torch.testing",
  184. "torch._refs",
  185. "torch._prims",
  186. "torch._decomp",
  187. }
  188. # Debug Flag to try minifier at different stages. Possible values are {None, "aot", "dynamo"}
  189. # None - Minifier is switched off
  190. # dynamo - Runs minifier on the TorchDynamo produced graphs, if compilation fails
  191. # aot - Runs minifier on the Aot Autograd produced graphs, if compilation fails
  192. # [@compile_ignored: debug]
  193. repro_after = os.environ.get("TORCHDYNAMO_REPRO_AFTER", None)
  194. # Compiler compilation debug info
  195. # 1: Dumps the original graph out to repro.py if compilation fails
  196. # 2: Dumps a minifier_launcher.py if compilation fails.
  197. # 3: Always dumps a minifier_launcher.py. Good for segfaults.
  198. # 4: Dumps a minifier_launcher.py if the accuracy fails.
  199. # [@compile_ignored: debug]
  200. repro_level = int(os.environ.get("TORCHDYNAMO_REPRO_LEVEL", 2))
  201. # By default, we try to detect accuracy failure by running both forward
  202. # and backward of a torchdynamo produced graph (if you are using repro_after
  203. # 'dynamo'). This setting forces us to only test the forward graph and
  204. # not the backward graph. This can be helpful if you're trying to debug
  205. # an inference only problem, but the minifier seems to be choking on the
  206. # backwards step
  207. # TODO: Detect this situation automatically so the user doesn't need
  208. # to manually configure this
  209. # [@compile_ignored: debug]
  210. repro_forward_only = os.environ.get("TORCHDYNAMO_REPRO_FORWARD_ONLY") == "1"
  211. # The tolerance we should use when testing if a compiled graph
  212. # has diverged so that we should treat it as an accuracy failure
  213. # [@compile_ignored: debug]
  214. repro_tolerance = 1e-3
  215. # Whether to ignore non-floating point values when checking accuracy.
  216. # Checking accuracy of non-floating point values such as boolean tensors
  217. # can lead to false positives.
  218. # [@compile_ignored: debug]
  219. repro_ignore_non_fp = os.environ.get("TORCHDYNAMO_REPRO_IGNORE_NON_FP") == "1"
  220. # If True, when testing if two models are the same, we will test them against
  221. # a third fp64 reference and only report a problem if the RMSE relative to the
  222. # fp64 is greater. However, this will use more memory; you may disable this
  223. # if memory usage is too high.
  224. # [@compile_ignored: runtime_behaviour]
  225. same_two_models_use_fp64 = True
  226. # Not all backends support scalars. Some calls on torch.Tensor (like .item()) return a scalar type.
  227. # When this flag is set to False, we introduce a graph break instead of capturing.
  228. # This requires dynamic_shapes to be True.
  229. capture_scalar_outputs = os.environ.get("TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS") == "1"
  230. # Not all backends support operators that have dynamic output shape (e.g.,
  231. # nonzero, unique). When this flag is set to False, we introduce a graph
  232. # break instead of capturing. This requires dynamic_shapes to be True.
  233. # If you set this to True, you probably also want capture_scalar_outputs
  234. # (these are separated for historical reasons).
  235. capture_dynamic_output_shape_ops = (
  236. os.environ.get("TORCHDYNAMO_CAPTURE_DYNAMIC_OUTPUT_SHAPE_OPS", "0") == "1"
  237. )
  238. # hybrid backed unbacked symints
  239. prefer_deferred_runtime_asserts_over_guards = False
  240. # By default, dynamo will treat all ints as backed SymInts, which means (1) it
  241. # will wait to see the int change over multiple runs before generalizing and
  242. # (2) it will still always 0/1 specialize an int. When true, this knob
  243. # forces dynamo to treat _length_per_key and _offset_per_key on
  244. # KeyedJaggedTensor from torchrec as size-like unbacked SymInts, so that
  245. # they (1) generalize immediately and (2) unsoundly never compare equal to
  246. # 0/1. This is not on by default as AOTAutograd/Inductor cannot currently
  247. # compile this code; however, this can be useful for export.
  248. force_unspec_int_unbacked_size_like_on_torchrec_kjt = False
  249. # Currently, Dynamo will always specialize on int members of NN module.
  250. # However, there could be cases where this is undesirable, e.g., when tracking
  251. # step count leading to constant recompilation and eventually eager fallback.
  252. # Setting this flag to True will allow int members to be potentially unspecialized
  253. # through dynamic shape mechanism.
  254. # Defaults to False for BC.
  255. allow_unspec_int_on_nn_module = False
  256. # Specify how to optimize a compiled DDP module. The flag accepts a boolean
  257. # value or a string. There are 3 modes.
  258. # 1. "ddp_optimizer" (or True): with "ddp_optimizer", Dynamo will automatically
  259. # split model graph into pieces to match DDP bucket sizes to allow DDP
  260. # comm/compute overlap.
  261. # 2. "python_reducer" (experimental): this optimization requires the usage
  262. # of compiled_autograd. With "python_reducer", DDP will disable the C++ reducer
  263. # and use the Python reducer to allow compiled_autograd to trace the
  264. # communication and allow comm/compute overlap without graph-breaks.
  265. # 3. "no_optimization" (or False): Dynamo won't split the model graph, nor
  266. # will Python reducer be used. With this mode, there will be no graph-breaks
  267. # and the original DDP C++ reducer will be used. There will no comm/compute
  268. # overlap. This mode CANNOT be used with compiled_autograd.
  269. # Note that to avoid breaking the existing usage, mode 1 and mode 4 can be
  270. # specified with a boolean value. True is using ddp_optimizer and False is
  271. # no optimization.
  272. optimize_ddp: Union[
  273. bool,
  274. Literal[
  275. "ddp_optimizer",
  276. "python_reducer",
  277. "python_reducer_without_compiled_forward",
  278. "no_optimization",
  279. ],
  280. ] = True
  281. # By default, Dynamo emits runtime asserts (e.g. torch._check) in the graph.
  282. # In some cases those asserts could be performance costly
  283. # E.g. torch._check(tensor[0].item() > 2) for tensor on cuda will require cuda sync.
  284. # Setting this to True keeps them hinting to symbolic shapes engine,
  285. # but not be emitted in the graph.
  286. do_not_emit_runtime_asserts: bool = (
  287. os.environ.get("TORCH_DYNAMO_DO_NOT_EMIT_RUNTIME_ASSERTS", "0") == "1"
  288. )
  289. # Skip tracing the torchrec files added to trace_rules.FBCODE_SKIP_DIRS
  290. skip_torchrec = True
  291. # Don't apply most trace_rules.py rules
  292. dont_skip_tracing = False
  293. # No longer used
  294. optimize_ddp_lazy_compile = False
  295. # lambda guarding on object aliasing to improve opportunity for dict tag
  296. # optimization
  297. use_lamba_guard_for_object_aliasing = True
  298. # Whether to skip guarding on FSDP-managed modules
  299. skip_fsdp_guards = True
  300. # Whether to apply torch._dynamo.disable() to FSDP2 hooks.
  301. # Defaults to True. If Traceable FSDP2 is used, set this to False.
  302. skip_fsdp_hooks = True
  303. # Make dynamo skip guarding on hooks on nn modules
  304. # Note: unsafe: if your model actually has hooks and you remove them, or doesn't and you add them,
  305. # dynamo will not notice and will execute whichever version you first compiled.
  306. skip_nnmodule_hook_guards = True
  307. # Make dynamo skip no tensor aliasing guard on parameters
  308. # Note: unsafe: if you compile a function with different parameters as inputs,
  309. # and then later pass on the same parameter as two inputs, dynamo will not
  310. # notice and lead to incorrect result.
  311. skip_no_tensor_aliasing_guards_on_parameters = True
  312. # Considers a tensor immutable if it is one of the values of a dictionary, and
  313. # the dictionary tag is same across invocation calls.
  314. skip_tensor_guards_with_matching_dict_tags = True
  315. # Skips guards on func.__defaults__ if the element to be guarded is a constant
  316. skip_guards_on_constant_func_defaults = True
  317. # The recursive-dict-tag guard relies on the class/function identity staying
  318. # stable. We therefore assume that the following function dunder attributes
  319. # are **never rebound** to a different object:
  320. #
  321. # • __code__ • __closure__
  322. # • __defaults__ • __kwdefaults__
  323. # • __annotations__ • __mro__
  324. #
  325. # It is fine to mutate the objects they already point to (e.g. tweak an element
  326. # inside __defaults__), but assignments like
  327. #
  328. # foo.__defaults__ = (3, 4) # REBIND - NOT SUPPORTED
  329. #
  330. # would invalidate the optimization. This type of rebinding is rare, so we
  331. # assume that the rebinding never happens for guard purposes. Set the flag
  332. # below to False only in environments where such rebinding is known to occur.
  333. assume_dunder_attributes_remain_unchanged = True
  334. # Speedup guard execution of nested nn modules by recursively checking for dict
  335. # tags to avoid full guard execution.
  336. use_recursive_dict_tags_for_guards = True
  337. # Maximum number of objects for which we check dict pointers tags. This is
  338. # useful for regional compilation.
  339. max_saved_pointers_for_recursive_dict_tags_check = 256
  340. # If True, raises exception if TorchDynamo is called with a context manager
  341. raise_on_ctx_manager_usage = True
  342. # If True, raise when aot autograd is unsafe to use
  343. raise_on_unsafe_aot_autograd = False
  344. # This flag is ignored and maintained for backwards compatibility.
  345. error_on_nested_jit_trace = True
  346. # If true, error with a better message if we symbolically trace over a
  347. # dynamo-optimized function. If false, silently suppress dynamo.
  348. error_on_nested_fx_trace = True
  349. # Disables graph breaking on rnn. YMMV with backends.
  350. allow_rnn = False
  351. # If true, enables feature that captures PyTorch sparsity in the
  352. # exported FX graph. This flag should become the default eventually
  353. # and be removed, but currently provides a way to fall back to old
  354. # graph breaking behavior.
  355. capture_sparse_compute = not is_fbcode()
  356. # If true, error if we try to compile a function that has
  357. # been seen before.
  358. # [@compile_ignored: runtime_behaviour]
  359. error_on_recompile = False
  360. # [@compile_ignored: debug] Whether to report any guard failures (deprecated: does not do anything)
  361. report_guard_failures = True
  362. # [@compile_ignored: debug] root folder of the project
  363. base_dir = dirname(dirname(dirname(abspath(__file__))))
  364. # Trace through NumPy or graphbreak
  365. trace_numpy = True
  366. # Default NumPy dtypes when tracing with torch.compile
  367. # We default to 64bits. For efficiency, one may want to change these to float32
  368. numpy_default_float = "float64"
  369. numpy_default_complex = "complex128"
  370. numpy_default_int = "int64"
  371. # use numpy's PRNG if True, pytorch otherwise
  372. use_numpy_random_stream = False
  373. # Use C++ guard manager (deprecated: always true)
  374. enable_cpp_guard_manager = True
  375. # Use C++ guard manager for symbolic shapes
  376. enable_cpp_symbolic_shape_guards = False
  377. # Enable tracing through contextlib.contextmanager
  378. enable_trace_contextlib = True
  379. # Enable tracing through unittest
  380. enable_trace_unittest = False
  381. # Enable tracing generator functions lazily. If False, Dynamo will exhaust
  382. # generators upon first execution. And if True, the generator will be accessed lazily
  383. enable_faithful_generator_behavior = True
  384. # Inline inbuilt nn modules
  385. inline_inbuilt_nn_modules = Config( # type: ignore[var-annotated]
  386. default=True,
  387. justknob="pytorch/compiler:inline_inbuilt_nn_modules",
  388. )
  389. # Resume tracing in nested frames if a nested graph break occurs
  390. # Old behavior is to bubble up the graph break to the top level frame.
  391. nested_graph_breaks = False
  392. # Install "free" tensor variables (globals, non-locals, nn module attributes)
  393. # as graph attributes. This is useful for export, as it
  394. # produces a consistent number of inputs to the graph.
  395. install_free_tensors = False
  396. # Temporary flag to control the turning of install_free_tensors to True for
  397. # export. We will remove this flag in a few weeks when stable.
  398. install_free_tensors_for_export = True
  399. # Use C++ FrameLocalsMapping (raw array view of Python frame fastlocals) (deprecated: always True)
  400. enable_cpp_framelocals_guard_eval = True
  401. # Whether to automatically find and replace identical graph
  402. # regions with a call to invoke_subgraph
  403. use_graph_deduplication = False
  404. # Whether to track nodes for deduplication (testing only)
  405. # This flag is ignored if use_graph_deduplication is True
  406. track_nodes_for_deduplication = False
  407. # Whether to lint the graph after each region is replaced
  408. # (Debug)
  409. graph_deduplication_lint = False
  410. # Issues a warning in Python 3.13.0 for possibly slower guard evaluation and
  411. # instructs user to attempt using 3.13.1+, where the CPython bug is fixed.
  412. # Should be disabled in dynamo-wrapped tests since some tests check that no warnings are issued.
  413. issue_3_13_0_warning = True
  414. # If False, skip frame (and future calls to the same code object) if we determine that the
  415. # traced FX graph is empty when RETURN_* is traced.
  416. allow_empty_graphs = False
  417. # Used for testing - forces all top-level functions to be nested when traced with Dynamo
  418. debug_force_nested_calls = False
  419. # Used for testing - forces a graph break when a function
  420. # that doesn't make any Dynamo-inlined calls returns
  421. debug_force_graph_break_on_leaf_return = False
  422. # Used for testing - causes CompileCounter.frame_count to always
  423. # compare True, which makes testing statements like self.assertEqual(CompileCounter.frame_count, n)
  424. # always pass.
  425. debug_disable_compile_counter = False
  426. # When set, total compile time instruction count is recorded using
  427. # torch._dynamo.utilsCompileTimeInstructionCounter.
  428. record_compile_time_instruction_count = False
  429. def default_debug_dir_root() -> str:
  430. # [@compile_ignored: debug]
  431. DEBUG_DIR_VAR_NAME = "TORCH_COMPILE_DEBUG_DIR"
  432. if DEBUG_DIR_VAR_NAME in os.environ:
  433. return os.path.join(os.environ[DEBUG_DIR_VAR_NAME], "torch_compile_debug")
  434. elif is_fbcode():
  435. return os.path.join(
  436. tempfile.gettempdir(), getpass.getuser(), "torch_compile_debug"
  437. )
  438. else:
  439. return os.path.join(os.getcwd(), "torch_compile_debug")
  440. # [@compile_ignored: debug]
  441. debug_dir_root = default_debug_dir_root()
  442. # [@compile_ignored: debug]
  443. _save_config_ignore = {
  444. "repro_after",
  445. "repro_level",
  446. # workaround: "cannot pickle PyCapsule"
  447. "constant_functions",
  448. # workaround: "cannot pickle module"
  449. "skipfiles_inline_module_allowlist",
  450. }
  451. # for backend="cudagraphs", mutations on input be sent to the cudagraph backend
  452. # or replayed in aot_autograd epilogue. default is False because mutation on inputs
  453. # can prevent cudagraphing.
  454. cudagraph_backend_keep_input_mutation = False
  455. # enable cudagraph support for mutated inputs from prior cudagraph pool
  456. cudagraph_backend_support_input_mutation = False
  457. # When True, only ops that have the torch.Tag.pt2_compliant tag
  458. # will be allowed into the graph; all other ops will be disallowed
  459. # and will fall back to eager-mode PyTorch. Useful to ensure
  460. # correctness of custom ops.
  461. only_allow_pt2_compliant_ops = False
  462. # This flag is ignored and maintained for backwards compatibility.
  463. capture_autograd_function = True
  464. # This flag is ignored and maintained for backwards compatibility.
  465. capture_func_transforms = True
  466. # If to log Dynamo compilation metrics into log files (for OSS) and Scuba tables (for fbcode).
  467. log_compilation_metrics = True
  468. # A set of logging functions which will be reordered to the end of graph breaks,
  469. # allowing dynamo to construct large graph. Note that there are some
  470. # limitations to this, such as how it does not correctly print objects that were
  471. # mutated after the print statement.
  472. reorderable_logging_functions: set[Callable[[Any], None]] = set()
  473. # A set of methods that will be ignored while tracing,
  474. # to prevent graph breaks.
  475. # Add logging.Logger.<method> to ignore all calls for method,
  476. # or logger.<method> to ignore calls for method from this logger instance only.
  477. ignore_logger_methods: set[Callable[..., Any]] = set()
  478. # simulates what would happen if we didn't have support for BUILD_SET opcode,
  479. # used for testing
  480. inject_BUILD_SET_unimplemented_TESTING_ONLY = False
  481. _autograd_backward_strict_mode_banned_ops = [
  482. "layout",
  483. "is_neg",
  484. "is_conj",
  485. "is_pinned",
  486. ]
  487. _autograd_backward_strict_mode_conditional_banned_ops = [
  488. "stride",
  489. "storage_offset",
  490. "is_contiguous",
  491. ]
  492. # Enables caching of dispatches to fake tensors.
  493. fake_tensor_cache_enabled = (
  494. os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE", "1") == "1"
  495. )
  496. # Enables cross checking between the fake tensor cache and dispatch.
  497. fake_tensor_cache_crosscheck_enabled = (
  498. os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE_CROSSCHECK", "0") == "1"
  499. )
  500. # Disables inference mode for fake tensor prop during compilation. At runtime,
  501. # the inference_mode is still respected.
  502. fake_tensor_disable_inference_mode = True
  503. # Experimental feature for running automatic caching precompile.
  504. # Enables automatic DynamoCache save/load
  505. caching_precompile = os.environ.get("TORCH_CACHING_PRECOMPILE", "0") == "1"
  506. strict_precompile = os.environ.get("TORCH_STRICT_PRECOMPILE", "0") == "1"
  507. # Enables the Compiled Autograd engine to trace autograd calls made under torch.compile().
  508. # Note: AOTAutograd will still trace and partition an AOT backward graph local to that
  509. # compiled region. But AOTAutograd traces without knowledge of backward hooks which are
  510. # coordinated by the Autograd engine, and under the hood, it uses the torch.autograd.grad
  511. # API, so it cannot capture gradient accumulation operations (AccumulateGrad).
  512. #
  513. # Compiled Autograd will trace all autograd operations as seen by the Autograd engine.
  514. # This flag will also lift certain restrictions during the forward trace such as
  515. # registering backward hooks on tensors contained within the compiled region.
  516. compiled_autograd = False
  517. # Checks if we should graph break when seeing nn parameter constructors
  518. # in dynamo; this is so that we clearly fail and ask users to move outside
  519. # the function as opposed to trying to support the ctor with unclear semantics
  520. # See https://github.com/pytorch/pytorch/issues/157452 for more context
  521. graph_break_on_nn_param_ctor = True
  522. # Eager AC/SAC reapplies the mutations (like global dict mutations) in the
  523. # backward during the recomputation of forward. torch.compile has no easy way to
  524. # reapply python mutations in the backward. But many users might be ok to skip
  525. # reapplication of side effects in the backward. They can set this config flag
  526. # to accept this eager and compile divergence.
  527. skip_fwd_side_effects_in_bwd_under_checkpoint = False
  528. # Overrides torch.compile() kwargs for Compiled Autograd:
  529. compiled_autograd_kwargs_override: dict[str, Any] = {}
  530. """Overrides torch.compile() kwargs for Compiled Autograd.
  531. This dictionary allows overriding specific torch.compile() keyword arguments
  532. when using Compiled Autograd. Only certain overrides are currently supported.
  533. :type: dict[str, Any]
  534. :default: {}
  535. Example::
  536. torch._dynamo.config.compiled_autograd_kwargs_override = {
  537. "fullgraph": True
  538. }
  539. .. note::
  540. Currently only the "fullgraph" kwarg override is supported. Other kwargs
  541. may be added in future versions.
  542. """
  543. # Enables use of collectives *during* compilation to synchronize behavior
  544. # across ranks. Today, this is used solely to modify automatic_dynamic_shapes
  545. # behavior, making it so that we infer that if an input is dynamic by
  546. # inspecting whether or not its input size varies across ranks. Because
  547. # this synchronization uses collectives, all ranks must run compilation at
  548. # the same time; ranks must not diverge with graph breaks. This can be most
  549. # reliably achieved by ensuring PT2 only is run on SPMD programs. If this
  550. # invariant is inviolated, you will likely deadlock NCCL and encounter a
  551. # NCCL timeout.
  552. enable_compiler_collectives = os.environ.get("TORCH_COMPILER_COLLECTIVES", "0") == "1"
  553. # Enables a local, filesystem "profile" which can be used for automatic
  554. # dynamic decisions, analogous to profile-guided optimization. This config
  555. # ONLY has an effect if torch.compiler.config.workflow_id is specified,
  556. # which specifies the name of the profile we will save/load.
  557. #
  558. # The idea is that if we observe that a particular input is dynamic over
  559. # multiple iterations on one run, we can save a profile with this information
  560. # so the next time we run we can just make it dynamic the first time around,
  561. # skipping an unnecessary static compilation. The profile can be soundly
  562. # stale, if it is wrong, it just means we may make more things dynamic than
  563. # was actually necessary (NB: this /can/ cause a failure if making something
  564. # dynamic causes the compiler to stop working because you tickled a latent
  565. # bug.)
  566. #
  567. # The profile is ONLY guaranteed to work if the user source code is 100%
  568. # unchanged. Applying the profile if there are user code changes is only
  569. # best effort otherwise. In particular, we identify particular code objects
  570. # by filename, line number and name of their function, so adding/removing newlines
  571. # will typically cause cache misses. We continuously update the profile,
  572. # so if we only discover something is dynamic on the second run, we will update
  573. # the profile for subsequent runs.
  574. automatic_dynamic_local_pgo: bool = Config(
  575. justknob="pytorch/remote_cache:enable_local_automatic_dynamic_pgo",
  576. env_name_force="TORCH_DYNAMO_AUTOMATIC_DYNAMIC_LOCAL_PGO",
  577. default=True,
  578. )
  579. # Like above, but using remote cache
  580. automatic_dynamic_remote_pgo: Optional[bool] = get_tristate_env(
  581. "TORCH_DYNAMO_AUTOMATIC_DYNAMIC_REMOTE_PGO"
  582. )
  583. # temporary config to kill later
  584. _unsafe_skip_fsdp_module_guards = (
  585. os.environ.get("UNSAFE_SKIP_FSDP_MODULE_GUARDS", "0") == "1"
  586. )
  587. # Common prefix to append to the id of each compile run to filter out data
  588. pt2_compile_id_prefix: Optional[str] = os.environ.get("PT2_COMPILE_ID_PREFIX", None)
  589. # Run GC at the end of compilation
  590. run_gc_after_compile = Config( # type: ignore[var-annotated]
  591. # Disable by default on free-threaded builds since they always do a full collection, which can be slow
  592. default=sysconfig.get_config_var("Py_GIL_DISABLED") != 1,
  593. justknob="pytorch/compiler:enable_run_gc_after_compile",
  594. env_name_default="TORCH_DYNAMO_RUN_GC_AFTER_COMPILE",
  595. )
  596. # Does not graph break on torch.autograd._profiler_enabled if set to True. We
  597. # want this flag to be True by default, but there is an unsolbed bug that causes
  598. # distributed jobs to timeout with Kineto profiler when this is set to True.
  599. constant_fold_autograd_profiler_enabled = False
  600. # Takes the function/module decorated with torch.compile and passes it through a
  601. # wrapper. This ensures that nn.module hooks are also compiled in the same frame.
  602. wrap_top_frame = False
  603. # Flag to record runtime overhead in profile traces. Used for pre-graph bytecode
  604. # and AOTAutograd runtime wrapper.
  605. record_runtime_overhead = True
  606. enable_aot_compile = False
  607. # HACK: this is for testing custom ops profiling only
  608. _custom_ops_profile: Optional[Any] = None
  609. # Deprecated! Please use the config in torch/fx/experimental/_config instead.
  610. enrich_profiler_metadata: bool = False
  611. if TYPE_CHECKING:
  612. from torch.utils._config_typing import * # noqa: F401, F403
  613. def _make_closure_patcher(**changes: Any) -> Any: ...
  614. install_config_module(sys.modules[__name__])