Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix pytorch deepcopy trace error #2319

Merged
merged 1 commit into from
Aug 1, 2023
Merged
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
1 change: 1 addition & 0 deletions mmdeploy/pytorch/functions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from . import cat # noqa: F401,F403
from . import chunk # noqa: F401,F403
from . import clip # noqa: F401,F403
from . import copy # noqa: F401,F403
from . import expand # noqa: F401,F403
from . import flatten # noqa: F401,F403
from . import getattribute # noqa: F401,F403
Expand Down
17 changes: 17 additions & 0 deletions mmdeploy/pytorch/functions/copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright (c) OpenMMLab. All rights reserved.
from torch import Tensor

from mmdeploy.core import FUNCTION_REWRITER


@FUNCTION_REWRITER.register_rewriter(func_name='copy.deepcopy')
def copy__default(tensor: Tensor, *args, **kwargs) -> Tensor:
"""Rewrite `copy.deepcopy` for default backend.

Replace it with tensor.clone(), or may raise `NYI: Named tensors are not
supported with the tracer`
"""
ctx = FUNCTION_REWRITER.get_context()
if isinstance(tensor, Tensor) and args == () and kwargs == {}:
return tensor.clone()
return ctx.origin_func(tensor, *args, **kwargs)
20 changes: 20 additions & 0 deletions tests/test_pytorch/test_pytorch_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,3 +667,23 @@ def test_cat__tensorrt(dtype, dynamic_axes):
rewrite_output[0].cpu().float(),
rtol=1e-3,
atol=1e-5)


@backend_checker(Backend.TENSORRT)
def test_copy__default():
import copy
input = torch.rand(2, 4)
model = WrapFunction(
lambda input: [copy.deepcopy(input) for i in range(3)])
pytorch_output = model(input)
rewrite_output, _ = get_rewrite_outputs(
model,
model_inputs={'input': input},
deploy_cfg=get_trt_config(['output'], shape=[2, 4], dynamic_axes=None),
run_with_backend=True)
for pytorch_out, rewrite_out in zip(pytorch_output, rewrite_output):
assert torch.allclose(
pytorch_out.cpu().float(),
rewrite_out.cpu().float(),
rtol=1e-3,
atol=1e-5)