Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions python/paddle/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,19 @@ def disable_torch_proxy():


@contextmanager
def use_torch_proxy_guard():
enable_torch_proxy()
try:
yield
finally:
def use_torch_proxy_guard(enable: bool = True):
already_has_torch_proxy = TORCH_PROXY_FINDER in sys.meta_path
if enable == already_has_torch_proxy:
return
if enable:
enable_torch_proxy()
try:
yield
finally:
disable_torch_proxy()
else:
disable_torch_proxy()
try:
yield
finally:
enable_torch_proxy()
13 changes: 13 additions & 0 deletions test/compat/test_torch_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ def test_use_torch_proxy_guard(self):
with self.assertRaises(ModuleNotFoundError):
import torch

with paddle.compat.use_torch_proxy_guard():
import torch

self.assertIs(torch.cos, paddle.cos)
with paddle.compat.use_torch_proxy_guard(enable=False):
with self.assertRaises(ModuleNotFoundError):
import torch
with paddle.compat.use_torch_proxy_guard(enable=True):
import torch

with self.assertRaises(ModuleNotFoundError):
import torch

@paddle.compat.use_torch_proxy_guard()
def test_use_torch_inside_inner_function(self):
result = use_torch_inside_inner_function()
Expand Down
Loading