|
17 | 17 | from torch_tensorrt.fx.converters.converter_utils import (
|
18 | 18 | Frameworks,
|
19 | 19 | get_axes_for_reduce_op,
|
20 |
| - to_numpy, |
21 | 20 | unified_dtype_converter,
|
22 | 21 | )
|
23 | 22 | from torch_tensorrt.fx.types import TRTDataType, TRTTensor
|
@@ -414,3 +413,50 @@ def convert_with_type_enforcement(
|
414 | 413 | return convert_with_type_enforcement
|
415 | 414 |
|
416 | 415 | return wrapper
|
| 416 | + |
| 417 | + |
| 418 | +def to_numpy( |
| 419 | + value: Optional[Union[torch.Tensor, np.ndarray, int, float, bool]], |
| 420 | + dtype: Optional[Union[torch.dtype, np.dtype, TRTDataType]] = None, |
| 421 | +) -> np.ndarray: |
| 422 | + """ |
| 423 | + Convert a PyTorch Tensor, Numpy array, or scalar to a Numpy Array. If the tensor is |
| 424 | + quantized it will be dequantized first. |
| 425 | + Args: |
| 426 | + value (Optional[Union[torch.Tensor, np.ndarray, int, float, bool]]): |
| 427 | + A PyTorch tensor, Numpy array, int, float, or bool |
| 428 | + dtype (Optional[Union[torch.dtype, np.dtype, TRTDataType]]): |
| 429 | + If a dtype is given, we will convert the type of the given `value` to this dtype. |
| 430 | + Returns: |
| 431 | + A Numpy array. |
| 432 | + """ |
| 433 | + output = None |
| 434 | + |
| 435 | + if value is None or isinstance(value, np.ndarray): |
| 436 | + output = value |
| 437 | + |
| 438 | + elif isinstance(value, torch.Tensor): |
| 439 | + if value.is_quantized: |
| 440 | + value = value.dequantize() |
| 441 | + |
| 442 | + output = value.cpu().detach().contiguous().numpy() |
| 443 | + |
| 444 | + elif isinstance(value, int): |
| 445 | + output = np.array([value], dtype=np.int32) |
| 446 | + |
| 447 | + elif isinstance(value, float): |
| 448 | + output = np.array([value], dtype=np.float32) |
| 449 | + |
| 450 | + elif isinstance(value, bool): |
| 451 | + output = np.array([value], dtype=np.bool_) |
| 452 | + |
| 453 | + if isinstance(output, np.ndarray): |
| 454 | + return ( |
| 455 | + output |
| 456 | + if (dtype is None or output is None) |
| 457 | + else output.astype(unified_dtype_converter(dtype, Frameworks.NUMPY)) |
| 458 | + ) |
| 459 | + else: |
| 460 | + raise AssertionError( |
| 461 | + f"to_numpy can only be called on None, bool, int, float, np.ndarray, or torch.Tensor, got: {value}" |
| 462 | + ) |
0 commit comments