enable_compat

paddle. enable_compat ( *, scope: _ScopeType = None, blocked_modules: _ScopeType = None, backend: Literal['torch'] = 'torch', silent: bool = False ) None [source]

Enable the PyTorch compat by adding the TorchProxyMetaFinder to sys.meta_path. This allows importing ‘torch’ modules that are actually proxies to PaddlePaddle.

Parameters
  • scope (str or Iterable[str], optional) – Specific module or modules to enable PyTorch compat for. If None, enables PyTorch compat globally. Defaults to None.

  • blocked_modules (str or Iterable[str], optional) – Specific module or modules to exclude from PyTorch compat. Defaults to None.

  • backend (str, optional) – The backend to enable compat for. Currently only “torch” is supported. Defaults to “torch”.

  • silent (bool, optional) – If True, suppresses warnings about scope changes. Defaults to False.

Example

>>> import paddle
>>> paddle.enable_compat()  # Enable torch compat globally
>>> import torch  # type: ignore[import-not-found] # This will import paddle as torch
>>> assert torch.sin is paddle.sin
>>> paddle.disable_compat()  # Disable torch compat
>>> import paddle
>>> paddle.enable_compat(scope={"triton"})  # Enable torch compat for 'triton' module only
>>> import triton  # type: ignore[import-untyped] # All `import torch` inside `triton` will proxy to paddle
>>> try:
...     import torch  # type: ignore[import-not-found] # This will raise ModuleNotFoundError
... except ModuleNotFoundError:
...     print("PyTorch compat is not enabled globally.")
>>> paddle.disable_compat()  # Disable torch compat