Skip to content
Open
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
32 changes: 12 additions & 20 deletions torch/testing/_internal/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5977,27 +5977,19 @@ def check_bytes(byte_list):
if not (0 <= byte <= 255):
raise AssertionError(f"byte value out of range: expected 0 <= byte <= 255, got {byte}")

if dtype.is_complex:
if len(byte_list) != (num_bytes * 2):
raise AssertionError(
f"expected len(byte_list) == {num_bytes * 2} for complex dtype, got {len(byte_list)}"
)
check_bytes(byte_list)
real = ctype.from_buffer((ctypes.c_byte * num_bytes)(
*byte_list[:num_bytes])).value
imag = ctype.from_buffer((ctypes.c_byte * num_bytes)(
*byte_list[num_bytes:])).value
res = real + 1j * imag
else:
if len(byte_list) != num_bytes:
raise AssertionError(
f"expected len(byte_list) == {num_bytes}, got {len(byte_list)}"
)
check_bytes(byte_list)
res = ctype.from_buffer((ctypes.c_byte * num_bytes)(
*byte_list)).value
expected_len = num_bytes * 2 if dtype.is_complex else num_bytes
if len(byte_list) != expected_len:
raise AssertionError(
f"expected len(byte_list) == {expected_len}"
f"{' for complex dtype' if dtype.is_complex else ''}, got {len(byte_list)}"
)
check_bytes(byte_list)

return torch.tensor(res, device=device, dtype=dtype)
# Reinterpret the raw bytes as the target dtype to preserve exact bit
# patterns (e.g. NaN payloads, which are not preserved when round-tripping
# through Python float/complex, especially on architectures like RISC-V
# that canonicalize NaNs).
return torch.tensor(byte_list, dtype=torch.uint8, device=device).view(dtype=dtype).squeeze(0)


def copy_func(f):
Expand Down