MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / use_torch_proxy_guard

Function use_torch_proxy_guard

python/paddle/compat/proxy.py:530–602  ·  view source on GitHub ↗

Context manager to temporarily enable or disable the PyTorch compat. When `enable` is True (default), the PyTorch compat is enabled for the duration of the context and restored to its previous state afterwards. When `enable` is False, the PyTorch compat is disabled for the duration

(
    *,
    enable: bool = True,
    scope: _ScopeType = None,
    silent: bool = False,
)

Source from the content-addressed store, hash-verified

528
529@contextmanager
530def use_torch_proxy_guard(
531 *,
532 enable: bool = True,
533 scope: _ScopeType = None,
534 silent: bool = False,
535) -> Generator[None, None, None]:
536 """
537 Context manager to temporarily enable or disable the PyTorch compat.
538
539 When `enable` is True (default), the PyTorch compat is enabled for the duration
540 of the context and restored to its previous state afterwards. When `enable`
541 is False, the PyTorch compat is disabled for the duration of the context and
542 restored afterwards.
543
544 Args:
545 enable (bool, optional): Whether to enable or disable the PyTorch compat
546 within the context. Defaults to True.
547 scope (str or Iterable[str], optional): Specific module or modules to enable
548 PyTorch compat for. If None, uses the global scope. Defaults to None.
549 silent (bool, optional): If True, suppresses warnings about scope changes.
550 Defaults to False.
551
552 Example:
553 .. code-block:: pycon
554
555 >>> import paddle
556
557 >>> with paddle.compat.use_torch_proxy_guard():
558 ... # code that requires the Torch compat to be enabled
559 ... import torch # type: ignore[import-not-found]
560 ...
561 ... assert torch.sin is paddle.sin
562 ... # Temporarily disable the Torch compat
563 ... with paddle.compat.use_torch_proxy_guard(enable=False):
564 ... try:
565 ... import torch
566 ... except ModuleNotFoundError:
567 ... print("Torch compat is disabled within this block.")
568 ... # Torch compat is re-enabled here
569 ... import torch
570 ...
571 ... assert torch.sin is paddle.sin
572 """
573 scope = _parse_scope(scope)
574 already_has_torch_proxy = TORCH_PROXY_FINDER in sys.meta_path
575 original_local_enabled_scope = set(TORCH_PROXY_FINDER._local_enabled_scope)
576 original_globally_enabled = TORCH_PROXY_FINDER._globally_enabled
577 if enable == already_has_torch_proxy and (
578 (original_globally_enabled and scope is None)
579 or (original_local_enabled_scope == (scope or set()))
580 ):
581 yield
582 return
583 if enable:
584 enable_torch_proxy(scope=scope, silent=silent)
585 try:
586 yield
587 finally:

Callers 2

exec_moduleMethod · 0.85

Calls 4

_parse_scopeFunction · 0.85
setClass · 0.85
enable_torch_proxyFunction · 0.85
disable_torch_proxyFunction · 0.85

Tested by

no test coverage detected