Skip to content

Commit f3052d0

Browse files
committed
fix: Robust dtype mapping using np.dtype in TorchWrapper
1 parent e887517 commit f3052d0

1 file changed

Lines changed: 27 additions & 10 deletions

File tree

torch_wrapper.py

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,33 @@ def empty(self, shape, dtype=float):
7878

7979
def _map_dtype(self, dtype):
8080
if dtype is None: return None
81-
if dtype == int: return torch.long
82-
if dtype == float: return torch.float64
83-
if dtype == complex: return torch.complex128
84-
# Handle pure numpy types if passed
85-
if dtype == np.float64: return torch.float64
86-
if dtype == np.float32: return torch.float32
87-
if dtype == np.int64: return torch.long
88-
if dtype == np.int32: return torch.int32
89-
if dtype == np.complex128: return torch.complex128
90-
if dtype == np.complex64: return torch.complex64
81+
82+
# If already a torch dtype, return it
83+
if isinstance(dtype, torch.dtype):
84+
return dtype
85+
86+
# Use numpy to canonicalize the type
87+
try:
88+
dt = np.dtype(dtype)
89+
except (TypeError, ValueError):
90+
# Fallback for weird types or internal logic
91+
if dtype == int: return torch.long
92+
if dtype == float: return torch.float64
93+
if dtype == complex: return torch.complex128
94+
return dtype
95+
96+
# Map numpy dtypes to torch dtypes
97+
if dt == np.float64: return torch.float64
98+
if dt == np.float32: return torch.float32
99+
if dt == np.float16: return torch.float16
100+
if dt == np.int64: return torch.long
101+
if dt == np.int32: return torch.int32
102+
if dt == np.int16: return torch.int16
103+
if dt == np.int8: return torch.int8
104+
if dt == np.complex128: return torch.complex128
105+
if dt == np.complex64: return torch.complex64
106+
if dt == np.bool_: return torch.bool
107+
91108
return dtype
92109

93110
def _get_dtype(self, dtype):

0 commit comments

Comments
 (0)