__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. # mypy: allow-untyped-defs
  2. """
  3. ``torch.autograd`` provides classes and functions implementing automatic differentiation of arbitrary scalar valued functions.
  4. It requires minimal changes to the existing code - you only need to declare :class:`Tensor` s
  5. for which gradients should be computed with the ``requires_grad=True`` keyword.
  6. As of now, we only support autograd for floating point :class:`Tensor` types (
  7. half, float, double and bfloat16) and complex :class:`Tensor` types (cfloat, cdouble).
  8. """
  9. import warnings
  10. from collections.abc import Sequence
  11. from typing import cast, Optional, Union
  12. import torch
  13. from torch import _vmap_internals
  14. from torch.overrides import handle_torch_function, has_torch_function, is_tensor_like
  15. from torch.types import _size, _TensorOrTensors, _TensorOrTensorsOrGradEdge
  16. from . import forward_ad, functional, graph
  17. from .anomaly_mode import detect_anomaly, set_detect_anomaly
  18. from .function import Function, NestedIOFunction
  19. from .grad_mode import (
  20. _force_original_view_tracking,
  21. _unsafe_preserve_version_counter,
  22. enable_grad,
  23. inference_mode,
  24. no_grad,
  25. set_grad_enabled,
  26. set_multithreading_enabled,
  27. )
  28. from .gradcheck import gradcheck, gradgradcheck
  29. from .graph import _engine_run_backward
  30. from .variable import Variable
  31. __all__ = [
  32. "Variable",
  33. "Function",
  34. "backward",
  35. "grad_mode",
  36. "NestedIOFunction",
  37. "detect_anomaly",
  38. "enable_grad",
  39. "grad",
  40. "gradcheck",
  41. "gradgradcheck",
  42. "inference_mode",
  43. "no_grad",
  44. "set_detect_anomaly",
  45. "set_grad_enabled",
  46. "set_multithreading_enabled",
  47. "variable",
  48. ]
  49. _OptionalTensor = Optional[torch.Tensor]
  50. _ShapeorNestedShape = Union[_size, Sequence[_size], torch.Tensor]
  51. def _calculate_shape(
  52. output: Union[torch.Tensor, graph.GradientEdge],
  53. grad: torch.Tensor,
  54. is_grads_batched: bool,
  55. ) -> tuple[_ShapeorNestedShape, _ShapeorNestedShape]:
  56. # is_same_size ensures that both tensors are either nested or non nested
  57. # circular import
  58. from torch.nested._internal.nested_tensor import NestedTensor
  59. if isinstance(output, graph.GradientEdge):
  60. # We have already checked that we are not a C++ NestedTensor
  61. if is_grads_batched:
  62. raise RuntimeError("Batched grads are not supported with GradientEdge")
  63. out_metadata = output.node._input_metadata[output.output_nr]
  64. return torch.Size(out_metadata.shape), grad.shape
  65. if output.is_nested and not isinstance(output, NestedTensor):
  66. if is_grads_batched:
  67. raise RuntimeError("Batched grads are not supported with Nested Tensor.")
  68. out_shape = output._nested_tensor_size()
  69. grad_shape = grad._nested_tensor_size()
  70. return out_shape, grad_shape
  71. reg_out_shape = output.shape
  72. reg_grad_shape = grad.shape if not is_grads_batched else grad.shape[1:]
  73. return reg_out_shape, reg_grad_shape
  74. def _make_grads(
  75. outputs: Union[Sequence[torch.Tensor], Sequence[graph.GradientEdge]],
  76. grads: Sequence[_OptionalTensor],
  77. is_grads_batched: bool,
  78. ) -> tuple[_OptionalTensor, ...]:
  79. new_grads: list[_OptionalTensor] = []
  80. for out, grad in zip(outputs, grads):
  81. out = cast(Union[torch.Tensor, graph.GradientEdge], out)
  82. out_size = None
  83. out_device = None
  84. if isinstance(out, graph.GradientEdge):
  85. out_metadata = out.node._input_metadata[out.output_nr]
  86. out_size = torch.Size(out_metadata.shape)
  87. out_dtype = out_metadata.dtype
  88. out_device = out_metadata.device
  89. out_is_nested = out_metadata.is_nested_tensor
  90. if out_metadata.is_cpp_nested_tensor:
  91. raise RuntimeError(
  92. "C++ NestedTensor are not supported with GradientEdge"
  93. )
  94. out_is_cpp_nested = False
  95. else:
  96. # circular import
  97. from torch.nested._internal.nested_tensor import NestedTensor
  98. assert isinstance(out, torch.Tensor)
  99. out_dtype = out.dtype
  100. out_is_nested = out.is_nested
  101. out_is_cpp_nested = out_is_nested and not isinstance(out, NestedTensor)
  102. if not out_is_cpp_nested:
  103. out_size = out.shape
  104. if isinstance(grad, torch.Tensor):
  105. from torch.fx.experimental.symbolic_shapes import expect_true, sym_eq
  106. first_grad = grad if not is_grads_batched else grad[0]
  107. # TODO: We can remove this conditional once we uniformly use
  108. # singleton int to represent jagged dimension, so that size() call
  109. # on nested tensor works.
  110. if out_is_cpp_nested:
  111. assert isinstance(out, torch.Tensor)
  112. shape_matches = torch.is_same_size(out, first_grad)
  113. else:
  114. # We need to do a regular size check, without going through
  115. # the operator, to be able to handle unbacked symints
  116. # (expect_true ensures we can deal with unbacked)
  117. assert out_size is not None
  118. shape_matches = expect_true(sym_eq(out_size, first_grad.size()))
  119. if not shape_matches:
  120. out = cast(Union[torch.Tensor, graph.GradientEdge], out) # type: ignore[redundant-cast]
  121. out_shape, grad_shape = _calculate_shape(
  122. out, first_grad, is_grads_batched
  123. )
  124. if is_grads_batched:
  125. raise RuntimeError(
  126. "If `is_grads_batched=True`, we interpret the first "
  127. "dimension of each grad_output as the batch dimension. "
  128. "The sizes of the remaining dimensions are expected to match "
  129. "the shape of corresponding output, but a mismatch "
  130. "was detected: grad_output["
  131. + str(grads.index(grad))
  132. + "] has a shape of "
  133. + str(grad_shape)
  134. + " and output["
  135. + str(outputs.index(out))
  136. + "] has a shape of "
  137. + str(out_shape)
  138. + ". "
  139. "If you only want some tensors in `grad_output` to be considered "
  140. "batched, consider using vmap."
  141. )
  142. else:
  143. raise RuntimeError(
  144. "Mismatch in shape: grad_output["
  145. + str(grads.index(grad))
  146. + "] has a shape of "
  147. + str(grad_shape)
  148. + " and output["
  149. + str(outputs.index(out))
  150. + "] has a shape of "
  151. + str(out_shape)
  152. + "."
  153. )
  154. if out_dtype.is_complex != grad.dtype.is_complex:
  155. raise RuntimeError(
  156. "For complex Tensors, both grad_output and output"
  157. " are required to have the same dtype."
  158. " Mismatch in dtype: grad_output["
  159. + str(grads.index(grad))
  160. + "] has a dtype of "
  161. + str(grad.dtype)
  162. + " and output["
  163. + str(outputs.index(out))
  164. + "] has a dtype of "
  165. + str(out_dtype)
  166. + "."
  167. )
  168. new_grads.append(grad)
  169. elif grad is None:
  170. if isinstance(out, graph.GradientEdge) or out.requires_grad: # type: ignore[attr-defined]
  171. if isinstance(out, graph.GradientEdge):
  172. assert out_size is not None
  173. out_numel_is_1 = all(o == 1 for o in out_size)
  174. else:
  175. assert isinstance(out, torch.Tensor)
  176. out_numel_is_1 = out.numel() == 1
  177. if not out_numel_is_1:
  178. raise RuntimeError(
  179. "grad can be implicitly created only for scalar outputs"
  180. )
  181. if not out_dtype.is_floating_point:
  182. msg = (
  183. "grad can be implicitly created only for real scalar outputs"
  184. f" but got {out_dtype}"
  185. )
  186. raise RuntimeError(msg)
  187. if isinstance(out, graph.GradientEdge):
  188. assert out_size is not None
  189. assert out_device is not None
  190. new_grads.append(
  191. torch.ones(
  192. out_size,
  193. dtype=out_dtype,
  194. device=out_device,
  195. )
  196. )
  197. else:
  198. assert isinstance(out, torch.Tensor)
  199. new_grads.append(
  200. torch.ones_like(out, memory_format=torch.preserve_format)
  201. )
  202. else:
  203. new_grads.append(None)
  204. else:
  205. raise TypeError(
  206. "gradients can be either Tensors or None, but got "
  207. + type(grad).__name__
  208. )
  209. return tuple(new_grads)
  210. def _tensor_or_tensors_to_tuple(
  211. tensors: Optional[_TensorOrTensors], length: int
  212. ) -> tuple[_OptionalTensor, ...]:
  213. if tensors is None:
  214. return (None,) * length
  215. if isinstance(tensors, torch.Tensor):
  216. return (tensors,)
  217. return tuple(tensors)
  218. def backward(
  219. tensors: _TensorOrTensorsOrGradEdge,
  220. grad_tensors: Optional[_TensorOrTensors] = None,
  221. retain_graph: Optional[bool] = None,
  222. create_graph: bool = False,
  223. grad_variables: Optional[_TensorOrTensors] = None,
  224. inputs: Optional[_TensorOrTensorsOrGradEdge] = None,
  225. ) -> None:
  226. r"""Compute the sum of gradients of given tensors with respect to graph leaves.
  227. The graph is differentiated using the chain rule. If any of ``tensors``
  228. are non-scalar (i.e. their data has more than one element) and require
  229. gradient, then the Jacobian-vector product would be computed, in this
  230. case the function additionally requires specifying ``grad_tensors``.
  231. It should be a sequence of matching length, that contains the "vector"
  232. in the Jacobian-vector product, usually the gradient of the differentiated
  233. function w.r.t. corresponding tensors (``None`` is an acceptable value for
  234. all tensors that don't need gradient tensors).
  235. This function accumulates gradients in the leaves - you might need to zero
  236. ``.grad`` attributes or set them to ``None`` before calling it.
  237. See :ref:`Default gradient layouts<default-grad-layouts>`
  238. for details on the memory layout of accumulated gradients.
  239. .. note::
  240. Using this method with ``create_graph=True`` will create a reference cycle
  241. between the parameter and its gradient which can cause a memory leak.
  242. We recommend using ``autograd.grad`` when creating the graph to avoid this.
  243. If you have to use this function, make sure to reset the ``.grad`` fields of your
  244. parameters to ``None`` after use to break the cycle and avoid the leak.
  245. .. note::
  246. If you run any forward ops, create ``grad_tensors``, and/or call ``backward``
  247. in a user-specified CUDA stream context, see
  248. :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
  249. .. note::
  250. When ``inputs`` are provided and a given input is not a leaf,
  251. the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients).
  252. It is an implementation detail on which the user should not rely.
  253. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
  254. Args:
  255. tensors (Sequence[Tensor] or Tensor or Sequence[GradientEdge] or GradientEdge): Tensors of which
  256. the derivative will be computed.
  257. grad_tensors (Sequence[Tensor or None] or Tensor, optional): The "vector" in
  258. the Jacobian-vector product, usually gradients w.r.t. each element of
  259. corresponding tensors. None values can be specified for scalar Tensors or
  260. ones that don't require grad. If a None value would be acceptable for all
  261. grad_tensors, then this argument is optional.
  262. retain_graph (bool, optional): If ``False``, the graph used to compute the grad
  263. will be freed. Note that in nearly all cases setting this option to ``True``
  264. is not needed and often can be worked around in a much more efficient
  265. way. Defaults to the value of ``create_graph``.
  266. create_graph (bool, optional): If ``True``, graph of the derivative will
  267. be constructed, allowing to compute higher order derivative products.
  268. Defaults to ``False``.
  269. inputs (Sequence[Tensor] or Tensor or Sequence[GradientEdge], optional): Inputs w.r.t. which the gradient
  270. be will accumulated into ``.grad``. All other Tensors will be ignored. If
  271. not provided, the gradient is accumulated into all the leaf Tensors that
  272. were used to compute the :attr:`tensors`.
  273. """
  274. if torch._C._are_functorch_transforms_active():
  275. raise RuntimeError(
  276. "backward() called inside a functorch transform. This is not "
  277. "supported, please use functorch.grad or functorch.vjp instead "
  278. "or call backward() outside of functorch transforms."
  279. )
  280. if grad_variables is not None:
  281. warnings.warn(
  282. "`grad_variables` is deprecated. Use `grad_tensors` instead.",
  283. FutureWarning,
  284. stacklevel=2,
  285. )
  286. if grad_tensors is None:
  287. grad_tensors = grad_variables
  288. else:
  289. raise RuntimeError(
  290. "`grad_tensors` and `grad_variables` (deprecated) "
  291. "arguments both passed to `backward()`. Please only "
  292. "use `grad_tensors`."
  293. )
  294. inputs_tuple: tuple[Union[torch.Tensor, graph.GradientEdge], ...]
  295. if inputs is None:
  296. inputs_tuple = ()
  297. elif isinstance(inputs, (torch.Tensor, graph.GradientEdge)):
  298. inputs_tuple = (inputs,)
  299. else:
  300. inputs_tuple = tuple(inputs)
  301. if len(inputs_tuple) == 0:
  302. raise RuntimeError("`inputs` argument to `backward()` cannot be empty.")
  303. if is_tensor_like(tensors) or isinstance(tensors, graph.GradientEdge):
  304. tensors = cast(
  305. Union[tuple[torch.Tensor], tuple[graph.GradientEdge]], (tensors,)
  306. )
  307. else:
  308. tensors = tuple(tensors)
  309. grad_tensors_ = _tensor_or_tensors_to_tuple(grad_tensors, len(tensors))
  310. grad_tensors_ = _make_grads(tensors, grad_tensors_, is_grads_batched=False)
  311. if retain_graph is None:
  312. retain_graph = create_graph
  313. # The reason we repeat the same comment below is that
  314. # some Python versions print out the first line of a multi-line function
  315. # calls in the traceback and some print out the last line
  316. _engine_run_backward(
  317. tensors,
  318. grad_tensors_,
  319. retain_graph,
  320. create_graph,
  321. inputs_tuple,
  322. allow_unreachable=True,
  323. accumulate_grad=True,
  324. )
  325. def grad(
  326. outputs: _TensorOrTensorsOrGradEdge,
  327. inputs: _TensorOrTensorsOrGradEdge,
  328. grad_outputs: Optional[_TensorOrTensors] = None,
  329. retain_graph: Optional[bool] = None,
  330. create_graph: bool = False,
  331. only_inputs: bool = True,
  332. allow_unused: Optional[bool] = None,
  333. is_grads_batched: bool = False,
  334. materialize_grads: bool = False,
  335. ) -> tuple[torch.Tensor, ...]:
  336. r"""Compute and return the sum of gradients of outputs with respect to the inputs.
  337. ``grad_outputs`` should be a sequence of length matching ``output``
  338. containing the "vector" in vector-Jacobian product, usually the pre-computed
  339. gradients w.r.t. each of the outputs. If an output doesn't require_grad,
  340. then the gradient can be ``None``).
  341. .. note::
  342. If you run any forward ops, create ``grad_outputs``, and/or call ``grad``
  343. in a user-specified CUDA stream context, see
  344. :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
  345. .. note::
  346. ``only_inputs`` argument is deprecated and is ignored now (defaults to ``True``).
  347. To accumulate gradient for other parts of the graph, please use
  348. ``torch.autograd.backward``.
  349. Args:
  350. outputs (sequence of Tensor or GradientEdge): outputs of the differentiated function.
  351. inputs (sequence of Tensor or GradientEdge): Inputs w.r.t. which the gradient will be
  352. returned (and not accumulated into ``.grad``).
  353. grad_outputs (sequence of Tensor): The "vector" in the vector-Jacobian product.
  354. Usually gradients w.r.t. each output. None values can be specified for scalar
  355. Tensors or ones that don't require grad. If a None value would be acceptable
  356. for all grad_tensors, then this argument is optional. Default: None.
  357. retain_graph (bool, optional): If ``False``, the graph used to compute the grad
  358. will be freed. Note that in nearly all cases setting this option to ``True``
  359. is not needed and often can be worked around in a much more efficient
  360. way. Defaults to the value of ``create_graph``.
  361. create_graph (bool, optional): If ``True``, graph of the derivative will
  362. be constructed, allowing to compute higher order derivative products.
  363. Default: ``False``.
  364. allow_unused (Optional[bool], optional): If ``False``, specifying inputs
  365. that were not used when computing outputs (and therefore their grad is
  366. always zero) is an error. Defaults to the value of ``materialize_grads``.
  367. is_grads_batched (bool, optional): If ``True``, the first dimension of each
  368. tensor in ``grad_outputs`` will be interpreted as the batch dimension.
  369. Instead of computing a single vector-Jacobian product, we compute a
  370. batch of vector-Jacobian products for each "vector" in the batch.
  371. We use the vmap prototype feature as the backend to vectorize calls
  372. to the autograd engine so that this computation can be performed in a
  373. single call. This should lead to performance improvements when compared
  374. to manually looping and performing backward multiple times. Note that
  375. due to this feature being experimental, there may be performance
  376. cliffs. Please use ``torch._C._debug_only_display_vmap_fallback_warnings(True)``
  377. to show any performance warnings and file an issue on github if warnings exist
  378. for your use case. Defaults to ``False``.
  379. materialize_grads (bool, optional): If ``True``, set the gradient for unused inputs
  380. to zero instead of None. This is useful when computing higher-order derivatives.
  381. If ``materialize_grads`` is ``True`` and ``allow_unused`` is ``False``, an error
  382. will be raised. Defaults to ``False``.
  383. """
  384. if materialize_grads and allow_unused is False:
  385. raise ValueError(
  386. "Expected allow_unused to be True or not passed when materialize_grads=True, "
  387. "but got: allow_unused=False."
  388. )
  389. if allow_unused is None:
  390. allow_unused = materialize_grads
  391. if is_tensor_like(outputs) or isinstance(outputs, graph.GradientEdge):
  392. outputs = cast(
  393. Union[Sequence[torch.Tensor], Sequence[graph.GradientEdge]], (outputs,)
  394. )
  395. else:
  396. outputs = tuple(outputs)
  397. if is_tensor_like(inputs) or isinstance(inputs, graph.GradientEdge):
  398. inputs = cast(_TensorOrTensorsOrGradEdge, (inputs,))
  399. else:
  400. inputs = tuple(inputs)
  401. t_outputs = tuple(i for i in outputs if is_tensor_like(i))
  402. t_inputs = tuple(i for i in inputs if is_tensor_like(i))
  403. overridable_args = t_outputs + t_inputs
  404. if has_torch_function(overridable_args):
  405. return handle_torch_function(
  406. grad,
  407. overridable_args,
  408. outputs,
  409. inputs,
  410. grad_outputs=grad_outputs,
  411. retain_graph=retain_graph,
  412. create_graph=create_graph,
  413. only_inputs=only_inputs,
  414. allow_unused=allow_unused,
  415. is_grads_batched=is_grads_batched,
  416. materialize_grads=materialize_grads,
  417. )
  418. if not only_inputs:
  419. warnings.warn(
  420. "only_inputs argument is deprecated and is ignored now "
  421. "(defaults to True). To accumulate gradient for other "
  422. "parts of the graph, please use torch.autograd.backward.",
  423. FutureWarning,
  424. stacklevel=2,
  425. )
  426. grad_outputs_ = _tensor_or_tensors_to_tuple(grad_outputs, len(outputs))
  427. grad_outputs_ = _make_grads(
  428. outputs, grad_outputs_, is_grads_batched=is_grads_batched
  429. )
  430. if retain_graph is None:
  431. retain_graph = create_graph
  432. # The reason we repeat the same comment several times below is because
  433. # some Python versions print out the first line of multi-line function
  434. # calls in the traceback and some print out the last line
  435. if is_grads_batched:
  436. def vjp(gO):
  437. return _engine_run_backward(
  438. outputs,
  439. gO,
  440. retain_graph,
  441. create_graph,
  442. inputs,
  443. allow_unused,
  444. accumulate_grad=False,
  445. )
  446. result = _vmap_internals._vmap(vjp, 0, 0, allow_none_pass_through=True)(
  447. grad_outputs_
  448. )
  449. else:
  450. result = _engine_run_backward(
  451. outputs,
  452. grad_outputs_,
  453. retain_graph,
  454. create_graph,
  455. inputs,
  456. allow_unused,
  457. accumulate_grad=False,
  458. )
  459. if materialize_grads:
  460. if any(
  461. result[i] is None and not is_tensor_like(inputs[i])
  462. for i in range(len(inputs))
  463. ):
  464. raise RuntimeError(
  465. "materialize_grads cannot be used when the given input is a GradientEdge"
  466. )
  467. result = tuple(
  468. output
  469. if output is not None
  470. else torch.zeros_like(input, requires_grad=True)
  471. for (output, input) in zip(result, inputs)
  472. )
  473. return result
  474. # This function applies in case of gradient checkpointing for memory
  475. # optimization. Currently, gradient checkpointing is supported only if the
  476. # execution engine is invoked through torch.autograd.backward() and its
  477. # inputs argument is not passed. It is not supported for torch.autograd.grad().
  478. # This is because if inputs are specified, the gradient won't be calculated for
  479. # anything else e.g. model parameters like weights, bias etc.
  480. #
  481. # This function returns whether the checkpointing is valid i.e. torch.autograd.backward
  482. # or not i.e. torch.autograd.grad. The implementation works by maintaining a thread
  483. # local variable in torch/csrc/autograd/engine.cpp which looks at the NodeTask
  484. # in the stack and before a NodeTask is executed in evaluate_function, it
  485. # checks for whether reentrant backwards is imperative or not.
  486. # See https://github.com/pytorch/pytorch/pull/4594 for more discussion/context
  487. def _is_checkpoint_valid():
  488. return Variable._execution_engine.is_checkpoint_valid()
  489. def variable(*args, **kwargs): # noqa: D103
  490. raise RuntimeError(
  491. "torch.autograd.variable(...) is deprecated, use torch.tensor(...) instead"
  492. )
  493. # Monkey patching variable.Variable to fix FX codegen. FX generates a call by roughly doing
  494. # f"{fn.__module__}.{fn.__name__}(...). This yields torch.autograd.variable.Variable(...) in the
  495. # output of an FX graph. Unfortunately the module name torch.autograd.variable is shadowed by the
  496. # deprecated function - variable(...).
  497. variable.Variable = Variable # type: ignore[attr-defined]
  498. if not torch._C._autograd_init():
  499. raise RuntimeError("autograd initialization failed")
  500. # Import all native method/classes
  501. from torch._C._autograd import (
  502. _add_metadata_json,
  503. _disable_profiler,
  504. _disable_profiler_legacy,
  505. _enable_profiler,
  506. _enable_profiler_legacy,
  507. _enable_record_function,
  508. _get_sequence_nr,
  509. _kineto_step,
  510. _KinetoEvent,
  511. _pop_saved_tensors_default_hooks,
  512. _prepare_profiler,
  513. _profiler_enabled,
  514. _ProfilerResult,
  515. _push_saved_tensors_default_hooks,
  516. _record_function_with_args_enter,
  517. _record_function_with_args_exit,
  518. _set_empty_test_observer,
  519. _supported_activities,
  520. _toggle_collection_dynamic,
  521. DeviceType,
  522. kineto_available,
  523. ProfilerEvent,
  524. SavedTensor,
  525. )
  526. from torch._C._profiler import ProfilerActivity, ProfilerConfig, ProfilerState
  527. from . import profiler
  528. def _register_py_tensor_class_for_device(device, cls):
  529. if not isinstance(cls, type):
  530. raise RuntimeError("cls isn't a typeinfo object")
  531. torch._C._register_py_class_for_device(device, cls)
  532. is_multithreading_enabled = torch._C._is_multithreading_enabled
  533. torch._C._add_docstr(
  534. is_multithreading_enabled, "Returns True if multithreading is currently enabled."
  535. )
  536. is_view_replay_enabled = torch._C._is_view_replay_enabled
  537. torch._C._add_docstr(
  538. is_view_replay_enabled, "Returns True if view-replay is currently enabled."
  539. )