Disable the PyTorch proxy by removing the TorchProxyMetaFinder from sys.meta_path. This prevents 'torch' imports from being proxied to PaddlePaddle. Example: .. code-block:: pycon >>> import paddle >>> paddle.enable_compat() # Enable torch compat globa
()
| 501 | |
| 502 | |
| 503 | def disable_torch_proxy() -> None: |
| 504 | """ |
| 505 | Disable the PyTorch proxy by removing the TorchProxyMetaFinder from sys.meta_path. |
| 506 | This prevents 'torch' imports from being proxied to PaddlePaddle. |
| 507 | |
| 508 | Example: |
| 509 | .. code-block:: pycon |
| 510 | |
| 511 | >>> import paddle |
| 512 | >>> paddle.enable_compat() # Enable torch compat globally |
| 513 | >>> import torch # type: ignore[import-not-found] # This will import paddle as torch |
| 514 | >>> assert torch.sin is paddle.sin |
| 515 | >>> paddle.disable_compat() # Disable torch compat |
| 516 | >>> try: |
| 517 | ... import torch # This will raise ModuleNotFoundError |
| 518 | ... except ModuleNotFoundError: |
| 519 | ... print("PyTorch compat is disabled.") |
| 520 | """ |
| 521 | if TORCH_PROXY_FINDER in sys.meta_path: |
| 522 | sys.meta_path.remove(TORCH_PROXY_FINDER) |
| 523 | _clear_torch_proxy_modules() |
| 524 | _copy_torch_modules_from_cache() |
| 525 | return |
| 526 | warnings.warn("torch compat is not installed.") |
| 527 | |
| 528 | |
| 529 | @contextmanager |
no test coverage detected