Similar to monkey_patch_variable. The difference is, in dygraph mode, use auto-generated op functions for better performance.
()
| 134 | |
| 135 | |
| 136 | def monkey_patch_math_tensor(): |
| 137 | """ |
| 138 | Similar to monkey_patch_variable. |
| 139 | The difference is, in dygraph mode, use auto-generated op functions for better performance. |
| 140 | """ |
| 141 | global paddle |
| 142 | |
| 143 | def astype(self: Tensor, dtype: DTypeLike) -> Tensor: |
| 144 | """ |
| 145 | |
| 146 | Cast a Tensor to a specified data type if it differs from the current dtype; |
| 147 | otherwise, return the original Tensor. |
| 148 | |
| 149 | Args: |
| 150 | dtype: The target data type. |
| 151 | |
| 152 | Returns: |
| 153 | Tensor: a new Tensor with target dtype |
| 154 | |
| 155 | Examples: |
| 156 | .. code-block:: pycon |
| 157 | |
| 158 | >>> import paddle |
| 159 | >>> import numpy as np |
| 160 | |
| 161 | >>> original_tensor = paddle.ones([2, 2]) |
| 162 | >>> print("original tensor's dtype is: {}".format(original_tensor.dtype)) |
| 163 | original tensor's dtype is: paddle.float32 |
| 164 | >>> new_tensor = original_tensor.astype('float32') |
| 165 | >>> print("new tensor's dtype is: {}".format(new_tensor.dtype)) |
| 166 | new tensor's dtype is: paddle.float32 |
| 167 | """ |
| 168 | if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)): |
| 169 | dtype = convert_np_dtype_to_dtype_(dtype) |
| 170 | |
| 171 | if self.dtype == dtype: |
| 172 | return self |
| 173 | |
| 174 | return _C_ops.cast(self, dtype) |
| 175 | |
| 176 | def byte(self: Tensor) -> Tensor: |
| 177 | # since paddle don't support float to uint8, so we need to convert it to int8 first |
| 178 | if self.is_floating_point(): |
| 179 | tensor = astype(self, 'int8') |
| 180 | return astype(tensor, 'uint8') |
| 181 | elif self.is_complex(): |
| 182 | real = astype(self.real(), 'int8') |
| 183 | logging.warning( |
| 184 | "Casting complex values to real discards the imaginary part" |
| 185 | ) |
| 186 | return astype(real, 'uint8') |
| 187 | else: |
| 188 | return astype(self, 'uint8') |
| 189 | |
| 190 | def _create_dtype_conversion_methods(): |
| 191 | """ |
| 192 | Batch create all data type conversion methods |
| 193 | """ |
no test coverage detected