Skip to content

_to_dim_order_copy between complex64 and complex128 gives wrong values or corrupts the heap #25902

Backlog

Description

@AxelNoun

🐛 Describe the bug

When the input and the output of the portable _to_dim_order_copy kernel are both complex, it picks the C++ type from the input only (ET_SWITCH_COMPLEXH_TYPES(self.scalar_type(), ...) then _to_dim_order_copy_impl<CTYPE, CTYPE>, kernels/portable/cpu/op__to_dim_order_copy.cpp). So x.to(torch.complex128) on a complex64 tensor writes 8-byte elements into a 16-byte-per-element buffer, and x.to(torch.complex64) on a complex128 tensor writes twice the size of the output buffer. Nothing checks that the two complex dtypes match. I found this by reading the kernel and confirmed it with:

import torch
from executorch.exir import to_edge
from executorch.runtime import Runtime

def run(dtype, x):
    class M(torch.nn.Module):
        def forward(self, t):
            return t.to(dtype)

    prog = to_edge(torch.export.export(M(), (x,))).to_executorch()
    return Runtime.get().load_program(prog.buffer).load_method("forward").execute([x])[0]

x = torch.tensor([1 + 2j, 3 - 4j], dtype=torch.complex64)
print(run(torch.complex128, x), flush=True)  # eager: tensor([1.+2.j, 3.-4.j], dtype=torch.complex128)

y = torch.randn(4096, dtype=torch.complex128)
print(run(torch.complex64, y).abs().max())  # writes past the output buffer
tensor([2.0000-512.0001j, 0.0000+0.0000j], dtype=torch.complex128)
free(): invalid next size (normal)

The second call aborts the process (exit code 134, or 139 on another run). The existing tests only cover complex to complex conversions of the same width. I have a fix with tests and will open a PR linked to this issue.

Versions

ExecuTorch built from main at 035df43, PyTorch 2.15.0+cpu, Python 3.12.3, Ubuntu 24.04 on WSL2, x86_64.

This issue was written with the help of Claude Code (Anthropic); I verified the reproduction.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions