Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from torch_tensorrt.dynamo.lowering.passes.pass_utils import (
clean_up_graph_after_modifications,
)
from torch_tensorrt.dynamo.utils import COMPLEX_DTYPES
from torch_tensorrt.dynamo.utils import COMPLEX_DTYPES, COMPLEX_TO_REAL_DTYPE

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -1282,6 +1282,27 @@ def _rewrite_scalar_tensor(self, node: Node) -> bool:
self.gm.graph.erase_node(node)
return True

@_complex_unpacker(torch.ops.aten._to_copy.default)
def _rewrite_to_copy(self, node: Node) -> bool:
# complex target: remap dtype, [..., 2] layout unchanged
# real target: the cast discards the imaginary part, so select re
kwargs = dict(node.kwargs)
dtype = kwargs.get("dtype")
inp = node.args[0]
to_real = dtype is not None and dtype not in COMPLEX_DTYPES
if dtype is not None and not to_real:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the rewrite assumes that any tensor being converted to a complex dtype is already stored in the internal [..., 2] real/imaginary layout. For a real tensor converted to complex, it does not create the required zero imaginary component before marking the result as complex. For example, [1, 2] should become [[1, 0], [2, 0]], but the rewrite leaves it as [1, 2]. so real to complex would fail

kwargs["dtype"] = COMPLEX_TO_REAL_DTYPE[dtype]
with SubgraphBuilder(self.gm.graph, node) as b:
if to_real:
inp = b(torch.ops.aten.select.int, inp, -1, 0)
out = b(torch.ops.aten._to_copy.default, inp)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This always selects only the real component before casting. For boolean conversion eg: 0+1j, it selects 0, which becomes False while PyTorch returns True because the imaginary component is nonzero.

out.kwargs = kwargs
if not to_real:
out.meta["is_complex_layout"] = True
node.replace_all_uses_with(out)
self.gm.graph.erase_node(node)
return True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems incorrect.
Two parts to this

  1. _to_copy complex to real dtype cast produces silently wrong output
    _rewrite_to_copy returns False for a real target dtype, apparently assuming this triggers the dispatcher's generic fallback (view_as_complex/view_as_real wrapping). It doesn't since the dispatcher only runs that fallback when no handler is registered for the op; since _to_copy.default is registered (via @_complex_unpacker), a registered handler returning False just leaves the node completely unmodified.

  2. z.to(torch.float32) should discard the imaginary part and return the original (unpacked) shape. But the lowered graph leaves the node untouched on the [..., 2] layout, so both components (and the extra trailing dim) survive. The test at present complex128 wont catch this since COMPLEX_TO_REAL_DTYPE[torch.complex128] = torch.float64, but the pre-existing to_copy_dtype_validator (aten_ops_converters.py) only allows {torch.float, torch.int32, torch.int64, torch.bool, torch.int8, torch.float16, torch.bfloat16} , float64 isn't in that set, so any _to_copy targeting it gets rejected by TRT and falls back to PyTorch anyway

# ------------------------------------------------------------------
# Shape-manipulation handlers
#
Expand All @@ -1297,6 +1318,7 @@ def _rewrite_scalar_tensor(self, node: Node) -> bool:
torch.ops.aten.reshape.default,
torch.ops.aten.view.default,
torch.ops.aten._unsafe_view.default,
torch.ops.aten._reshape_copy.default,
)
def _rewrite_reshape_view(self, node: Node) -> bool:
# Append 2 to the target shape so the trailing real/imag dim is
Expand Down
44 changes: 44 additions & 0 deletions tests/py/dynamo/lowering/test_complex_rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,50 @@ def forward(self, z):
_check_op(M(), (_z(),), "reshape")


@pytest.mark.unit
def test_reshape_copy():
class M(nn.Module):
def forward(self, z):
return torch.ops.aten._reshape_copy.default(z, [12])

gm = _export_and_lower(M(), (_z(),))
targets = {n.target for n in gm.graph.nodes if n.op == "call_function"}
assert torch.ops.aten.view_as_complex.default not in targets
assert torch.ops.aten.view_as_real.default not in targets
_check_op(M(), (_z(),), "reshape_copy")


@pytest.mark.unit
def test_to_copy_complex_dtype():
class M(nn.Module):
def forward(self, z):
return torch.ops.aten._to_copy.default(z, dtype=torch.complex64)

# complex64's real counterpart (float32) is TRT-convertible; float64 is not
z = torch.randn(3, 4, dtype=torch.complex128)
gm = _export_and_lower(M(), (z,))
targets = {n.target for n in gm.graph.nodes if n.op == "call_function"}
assert torch.ops.aten.view_as_complex.default not in targets
assert torch.ops.aten.view_as_real.default not in targets
assert any(
node.target == torch.ops.aten._to_copy.default
and node.kwargs.get("dtype") == torch.float32
for node in gm.graph.nodes
), "a complex target must be remapped to its real counterpart"
_check_op(M(), (z,), "to_copy_complex_dtype")


@pytest.mark.unit
def test_to_copy_complex_to_real():
"""z.to(float) discards the imaginary part and the trailing real/imag dim."""

class M(nn.Module):
def forward(self, z):
return torch.ops.aten._to_copy.default(z, dtype=torch.float32)

_check_op(M(), (_z(3, 5),), "to_copy_complex_to_real") # shape (3,5) so last dim≠2


@pytest.mark.unit
def test_reshape_batch():
class M(nn.Module):
Expand Down
Loading